我完全迷失在 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; } }
...
ViewModelBase
实现INotifyPropertyChanged
接口下面是如何Button
绑定到命令的:
<Button Content="Save" Margin="3" Command="{Binding DataContext.Save}" />
的实例CustomerViewModel
分配给DataContext
包含 的窗口Button
。
给定的示例不起作用:我在方法中设置了断点,Save
但执行没有传递给方法。我看过很多例子(在stackoverflow上也是),但不知道应该如何指定绑定。
请告知,任何帮助将不胜感激。
谢谢。
PS可能我需要RelativeSource
在按钮绑定中指定......像这样:
Command="{Binding Path=DataContext.Save, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
但是应该为祖先指定哪种类型?