2

WPF アプリケーションの MVVM を理解しようとしています

以下の例では、ICommand から継承するデリゲートを使用し、ViewModel でデリゲートをインスタンス化し、適切な実装を提供します。

私の質問は、ViewModel に ICommand を実装させることができないのはなぜですか?

ビューモデル:

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        InitializeViewModel();
    }

    protected void InitializeViewModel()
    {
        DelegateCommand MyCommand = new DelegateCommand<SomeClass>(
            SomeCommand_Execute, SomeCommand_CanExecute);    
    }

    void SomeCommand_Execute(SomeClass arg)
    {
        // Implementation
    }

    bool SomeCommand_CanExecute(SomeClass arg)
    {
        // Implementation
    }
}

デリゲートコマンド:

public class DelegateCommand<T> : ICommand
{
    public DelegateCommand(Action<T> execute) : this(execute, null) { }

    public DelegateCommand(Action<T> execute, Predicate<T> canExecute) : this(execute, canExecute, "") { }

    public DelegateCommand(Action<T> execute, Predicate<T> canExecute, string label)
    {
        _Execute = execute;
        _CanExecute = canExecute;
    }
.
.
.
}
4

3 に答える 3

3

その理由は、ビューとコマンドの数の間に1対多の関係があるためです。

通常、ビューごとに1つのViewModelがあります。ただし、1つのビューに多くのコマンドが必要な場合があります。ViewModelをコマンドとして使用する場合は、ViewModelの複数のインスタンスが必要になります。

典型的な実装は、ViewModelにViewが必要とするすべてのコマンドのインスタンスが含まれることです。

于 2013-03-13T18:00:21.500 に答える
3

簡単な答え: ViewModel はコマンドではないためです。

さらに、ViewModel は複数のコマンドを保持できます。

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        InitializeViewModel();

        OpenCommand = new DelegateCommand<SomeClass>(
            param => { ... },
            param => { return true; }); 

        SaveCommand = new DelegateCommand<SomeClass>(
            param => { ... },
            param => { return true; });

        SaveAsCommand = new DelegateCommand<SomeClass>(
            param => { ... },
            param => { return true; });
    }

    public ICommand OpenCommand { get; private set; }

    public ICommand SaveCommand { get; private set; }

    public ICommand SaveAsCommand { get; private set; }
}

これらのコマンドはプロパティであるため、ビューにバインドできます。

于 2013-03-13T18:03:13.930 に答える
0

この方法で実装できます。ICommandこれは、を実装する非常に一般的な方法ですICommand。そうは言ってもMyCommand、ViewModelにバインドするには、ViewModelにプロパティを作成する必要があります。

于 2013-03-13T17:59:21.440 に答える