【发布时间】:2011-01-06 20:42:01
【问题描述】:
我完全迷失在 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 的一个实例分配给包含Button 的窗口的DataContext。
给定的示例不起作用:我已经在Save 方法中设置了断点,但执行没有传递给该方法。我看过很多例子(也在 stackoverflow 上),但不知道应该如何指定绑定。
请告知,任何帮助将不胜感激。
谢谢。
附:可能我需要在 Button 绑定中指定 RelativeSource... 像这样:
Command="{Binding Path=DataContext.Save, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
但是应该为祖先指定哪种类型?
【问题讨论】:
-
程序的输出是否有绑定错误?绑定错误通常未被发现。您还应该尝试 Snoop。它是一个附加到您正在运行的应用程序的工具,还可以发现绑定错误。
标签: wpf binding mvvm commandbinding