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

时间:2012-02-12 02:51:05

标签: c# wpf mvvm mdi relaycommand

我正在使用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个或更多这样的命令,所以我现在想以正确的方式做到这一点。 有没有办法阻止这种或更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

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

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

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

此外,如果我正确理解您的代码,它的规定如果CurrentChildViewModel属性为null,则该命令将被禁用。 如果您需要这样的行为,您应该将此转换器添加到您的代码中并稍微重写绑定:

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}}" />