防止 MVVM/MDI 应用程序中出现几乎重复的 RelayCommands
我正在使用 MDI 解决方案(请参阅 http://wpfmdi.codeplex.com/)和 MVVM。
我使用一个 RelayCommand 将工具栏和/或菜单绑定到主 ViewModel,例如:
ICommand _editSelectedItemCommand;
public ICommand EditSelectedItemCommand
{
get
{
return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => CurrentChildViewModel.EditSelectedItem(),
param => ((CurrentChildViewModel != null) && (CurrentChildViewModel.CanExecuteEditSelectedItem))));
}
}
但是,在子窗口中,要将按钮绑定到相同的功能,我需要另一个 RelayCommand,它几乎相同,只是它调用方法 EditSelectedItem 和 CanExecuteEditSelectedItem直接地。它看起来像:
ICommand _editSelectedItemCommand;
public ICommand EditSelectedItemCommand
{
get
{
return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => EditSelectedItem(),
param => CanExecuteEditSelectedItem))));
}
}
我需要大约 10 个,将来可能需要 50 个或更多这样的命令,所以我喜欢现在就以正确的方式执行。 有没有办法防止这种情况或有更好的方法来做到这一点?
I'm using an MDI solution (see http://wpfmdi.codeplex.com/) and MVVM.
I use one RelayCommand to bind the toolbar and/or menu to the Main ViewModel, like:
ICommand _editSelectedItemCommand;
public ICommand EditSelectedItemCommand
{
get
{
return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => CurrentChildViewModel.EditSelectedItem(),
param => ((CurrentChildViewModel != null) && (CurrentChildViewModel.CanExecuteEditSelectedItem))));
}
}
However, in the child window, to bind a button to the same functionality I need another RelayCommand which is almost equal except it calls the methods EditSelectedItem and CanExecuteEditSelectedItem directly. It would look like:
ICommand _editSelectedItemCommand;
public ICommand EditSelectedItemCommand
{
get
{
return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => EditSelectedItem(),
param => CanExecuteEditSelectedItem))));
}
}
I need about 10 and in the future maybe 50 or more of such commands so I like to do it the right way now.
Is there a way to prevent this or a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以从主视图模型中删除第一个命令,因为子视图模型中的命令已经足够了。
只需在 xaml 标记中使用这样的绑定即可:
另外,如果我正确理解您的代码,它规定如果
CurrentChildViewModel
属性为 null,则该命令将被禁用。如果您需要这样的行为,您应该将此转换器添加到您的代码中并稍微重写绑定:
XAML:
You can remove the first command from the main viewmodel, because the command in the child viewmodel is more than enough.
Just use the binding like this in the xaml markup:
Also if I understand your code correctly, it has the stipulation that if the
CurrentChildViewModel
property is null than the command will be disabled.If you need such behavior, you should add this converter to your code and slightly rewrite the binding:
XAML: