1

MDIソリューション(http://wpfmdi.codeplex.com/を参照)とMVVMを使用しています。

次のように、1つのRelayCommandを使用してツールバーやメニューをメインViewModelにバインドします。

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

ただし、子ウィンドウでボタンを同じ機能にバインドするには、メソッドEditSelectedItemとCanExecuteEditSelectedItemを直接呼び出すことを除いて、ほぼ同じ別のRelayCommandが必要です。次のようになります。

 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プロパティが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}}" />
于 2012-02-12T16:13:49.323 に答える