3

我完全迷失在 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}}}"

但是应该为祖先指定哪种类型?

4

1 回答 1

10

您要做的是直接绑定到 Save 方法。这不是如何做到的。

假设您已将 View 的 DataContext 设置为 CustomerViewModel 的实例,这就是您绑定到 SaveCommand 的方式:

<Button Content="Save" Margin="3" Command="{Binding SaveCommand}" />

你不必打电话NotifyPropertyChanged("SaveCommand");

于 2010-01-19T15:27:13.820 回答