Bud*_*dda 3 wpf binding mvvm commandbinding
我完全迷失在MVVM中使用的命令绑定中.我应该如何将我的对象绑定到窗口和/或它的命令控件来获取方法Button Click?
这是一CustomerViewModel堂课:
public class CustomerViewModel : ViewModelBase
{
RelayCommand _saveCommand;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(param => this.Save(), param => this.CanSave);
NotifyPropertyChanged("SaveCommand");
}
return _saveCommand;
}
}
public void Save()
{
...
}
public bool CanSave { get { return true; } }
...
Run Code Online (Sandbox Code Playgroud)
ViewModelBase实现INotifyPropertyChanged接口以下是Button命令的绑定方式:
<Button Content="Save" Margin="3" Command="{Binding DataContext.Save}" />
Run Code Online (Sandbox Code Playgroud)
将一个实例CustomerViewModel分配给DataContext包含a的窗口Button.
给定的示例不起作用:我已将断点放入Save方法中,但执行不会传递给方法.我已经看到很多例子(在stackoverflow上也是如此),但是无法弄清楚应该如何指定绑定.
请指教,任何帮助将不胜感激.
谢谢.
PS可能我需要RelativeSource在Button绑定中指定......这样的事情:
Command="{Binding Path=DataContext.Save, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
Run Code Online (Sandbox Code Playgroud)
但是应该为祖先指定哪种类型?
Jak*_*sen 10
您要做的是直接绑定到Save方法.这不是怎么做的.
假设您已将View的DataContext设置为CustomerViewModel的实例,这就是绑定到SaveCommand的方式:
<Button Content="Save" Margin="3" Command="{Binding SaveCommand}" />
Run Code Online (Sandbox Code Playgroud)
你不必打电话NotifyPropertyChanged("SaveCommand");.
| 归档时间: |
|
| 查看次数: |
6603 次 |
| 最近记录: |