gpt4 book ai didi

mvvm - MVVM 中的 Silverlight 多命令绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 10:40:32 26 4
gpt4 key购买 nike

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

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

在 View 模型类中,我实现了以下代码;
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();
}
}

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

最佳答案

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 属性绑定(bind)到 SomeCommand .您还可以将 CommandParameter 绑定(bind)到某个东西,它将作为参数传递给 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();
}
}

关于mvvm - MVVM 中的 Silverlight 多命令绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4837804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com