c# - 防止 MVVM/MDI 应用程序中几乎重复的 RelayCommands

标签 c# wpf mvvm mdi relaycommand

我正在使用 MDI 解决方案(参见 http://wpfmdi.codeplex.com/)和 MVVM。

我使用一个 RelayCommand 将工具栏和/或菜单绑定(bind)到主 ViewModel,例如:

 ICommand _editSelectedItemCommand;
    public ICommand EditSelectedItemCommand
    {
        get
        {
            return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => CurrentChildViewModel.EditSelectedItem(),
                param => ((CurrentChildViewModel != null) && (CurrentChildViewModel.CanExecuteEditSelectedItem))));
        }
    }

但是,在子窗口中,要将按钮绑定(bind)到相同的功能,我需要另一个几乎相等的 RelayCommand,除了它直接调用方法 EditSelectedItem 和 CanExecuteEditSelectedItem 。它看起来像:
 ICommand _editSelectedItemCommand;
    public ICommand EditSelectedItemCommand
    {
        get
        {
            return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => EditSelectedItem(),
                param => CanExecuteEditSelectedItem))));
        }
    }

我需要大约 10 个,将来可能需要 50 个或更多这样的命令,所以我现在喜欢用正确的方式来做。
有没有办法防止这种情况或更好的方法来做到这一点?

最佳答案

您可以从主视图模型中删除第一个命令,因为 subview 模型中的命令绰绰有余。

只需在 xaml 标记中使用这样的绑定(bind):

<Button Command="{Binding CurrentChildViewModel.EditSelectedItemCommand}" 
        Content="Button for the main view model" />

此外,如果我正确理解您的代码,则规定如果 CurrentChildViewModel属性为空,该命令将被禁用。
如果您需要这样的行为,您应该将此转换器添加到您的代码中并稍微重写绑定(bind):
public class NullToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value != null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:
<Application.Resources>
    <local:NullToBooleanConverter x:Key="NullToBooleanConverter" />
</Application.Resources>
<!-- your control -->
<Button Command="{Binding CurrentChildViewModel.EditSelectedItemCommand}" 
        IsEnabled="{Binding CurrentChildViewModel, Converter={StaticResource NullToBooleanConverter}}" />

关于c# - 防止 MVVM/MDI 应用程序中几乎重复的 RelayCommands,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9246027/

相关文章:

c# - 函数参数中的 "this"

WPF:用于显示数据的网格的替代方案?

Android MVVM 模式 - 用户输入

c# - Action 的结果是什么?我该如何使用它?

c# - 为什么两个操作数都没有提升为 float 或 double 而不是错误?

c# - 将 DataGridView 控件中列的数据绑定(bind)到 .NET Chart 控件

c# - Animation Completed 稍微到很快就会触发

wpf - 在父级内部移动子级

c# - 从 Blend 中的类创建样本数据抛出 "Object reference not set to an instance of an object "

wpf - 从选项卡内部将选项卡添加到选项卡控件