1

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

4

1 回答 1

2

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

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

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

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

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}}" />
于 2012-02-12T16:13:49.323 回答