我完全迷失在 MVVM 中使用的命令绑定(bind)。我应该如何将我的对象绑定(bind)到窗口和/或其命令到控件以获取在 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
接口(interface)
以下是 Button
绑定(bind)到命令的方式:
<Button Content="Save" Margin="3" Command="{Binding DataContext.Save}" />
CustomerViewModel
的一个实例被分配给包含 Button
的窗口的 DataContext
。
给定的示例不起作用:我已在 Save
方法中设置了断点,但执行未传递给该方法。我看过很多例子(也在 stackoverflow 上),但不知道应该如何指定绑定(bind)。
请告知,任何帮助将不胜感激。
谢谢。
附:可能我需要在 Button 绑定(bind)中指定 RelativeSource
......像这样:
Command="{Binding Path=DataContext.Save, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
但是应该为祖先指定哪种类型?
最佳答案
您尝试做的是直接绑定(bind)到 Save 方法。这不是怎么做的。
假设您已将 View 的 DataContext 设置为 CustomerViewModel 的实例,这就是您绑定(bind)到 SaveCommand 的方式:
<Button Content="Save" Margin="3" Command="{Binding SaveCommand}" />
您不必调用 NotifyPropertyChanged("SaveCommand");
。
关于WPF MVVM : ICommand Binding to controls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2094532/