1

我开始使用 MVVM 构建 Silverlight 应用程序。我在 XAML 页面上有一个按钮,可以在单击时保存数据我已经编写了以下代码。

 <Button Content="Save" Grid.Column="2" Grid.Row="3"
                    Command="{Binding Path=SaveCourse}"/>

在视图模型类中,我实现了以下代码;

public class SaveCurrentCourse : ICommand
        {
            private MaintenanceFormViewModel viewModel;
            public SaveCurrentCourse(MaintenanceFormViewModel viewModel)
            {
                this.viewModel = viewModel;
                this.viewModel.PropertyChanged += (s, e) =>
                    {
                        if (this.CanExecuteChanged != null)
                        {
                            this.CanExecuteChanged(this, new EventArgs());
                        }
                    };   
            }
            public bool CanExecute(object parameter)
            {
                return this.viewModel.CurrentCourse != null;
            }

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
                this.viewModel.SaveCourseImplementation();
            }
        }

哪种适用于我的保存命令。我的问题是如果页面上有多个按钮,那么我是否必须为每个按钮编写与上面相同的代码?任何机构都可以提出更好的方法吗?

4

1 回答 1

1

Microsoft 的模式和实践团队提供了一个名为 Prism 的库,可以稍微简化这一点。http://compositewpf.codeplex.com/

它们提供了一个名为的类,该类DelegateCommand实现ICommand并允许您传递您希望执行的方法名称。

public class Test {
    public Test(){
        SomeCommand = new DelegateCommand<object>(DoSomething);
    }
    public DelegateCommand<object> SomeCommand { get; private set;}
    private void DoSomething(object parameter){
        //Do some stuff
    }
}

然后,您可以将控件的 Command 属性绑定到SomeCommand. 您还可以将 CommandParameter 绑定到某个东西,它将作为参数传递给 DoSomething 方法。DelegateCommand 的附加构造函数允许您将 CanExecute 方法作为第二个参数传递,这将启用/禁用控件。如果需要更新控件的启用/禁用状态,可以调用 DelegateCommand 的RaiseCanExecuteChanged()方法。

public class Test {
    public Test(){
        SomeCommand = new DelegateCommand<object>(DoSomething, (enabled) => CanSave());
    }
    public DelegateCommand<object> SomeCommand { get; private set;}
    private void DoSomething(object parameter){
        //Do some stuff
    }
    private bool CanSave(){
        if(/*test if the control should be enabled */)
            return true;
        else
            return false;
    }
    private void DoABunchOfStuff(){
        //something here means the control should be disabled
        SomeCommand.RaiseCanExecuteChanged();
    }
}
于 2011-01-29T17:10:46.130 回答