4

私はちょうど Silverlight を学んでいて、MVVM と Commanding を見ています。

OK、基本的な RelayCommand の実装を見てきました。

public class RelayCommand : ICommand
{
    private readonly Action _handler;
    private bool _isEnabled;

    public RelayCommand(Action handler)
    {
        _handler = handler;
    }

    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            if (value != _isEnabled)
            {
                _isEnabled = value;
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, EventArgs.Empty);
                }
            }
        }
    }

    public bool CanExecute(object parameter)
    {
        return IsEnabled;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _handler();
    }
}

これを使用してコマンドでパラメーターを渡すにはどうすればよいですか?

次のように渡すことができることがわかりましたCommandParameter

<Button Command="{Binding SomeCommand}" CommandParameter="{Binding SomeCommandParameter}" ... />

私の ViewModel では、コマンドを作成する必要がありますがRelayCommandActionデリゲートが必要です。RelayCommand<T>を使用して実装できますかAction<T>- もしそうなら、どのようにそれを行い、どのように使用するのですか?

既存のライブラリを使用する前に完全に理解したいので、サードパーティのライブラリ (MVVM Light など) を使用しない MVVM を使用した CommandParameters の実用的な例を教えてください。

ありがとう。

4

2 に答える 2

4
public class Command : ICommand
{
    public event EventHandler CanExecuteChanged;

    Predicate<Object> _canExecute = null;
    Action<Object> _executeAction = null;

    public Command(Predicate<Object> canExecute, Action<object> executeAction)
    {
        _canExecute = canExecute;
        _executeAction = executeAction;
    }
    public bool CanExecute(object parameter)
    {
        if (_canExecute != null)
            return _canExecute(parameter);
        return true;
    }

    public void UpdateCanExecuteState()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, new EventArgs());
    }

    public void Execute(object parameter)
    {
        if (_executeAction != null)
            _executeAction(parameter);
        UpdateCanExecuteState();
    }
}

コマンドの基本クラスです

そして、これは ViewModel のコマンド プロパティです。

 private ICommand yourCommand; ....

 public ICommand YourCommand
    {
        get
        {
            if (yourCommand == null)
            {
                yourCommand = new Command(  //class above
                    p => true,    // predicate to check "CanExecute" e.g. my_var != null
                    p => yourCommandFunction(param1, param2));
            }
            return yourCommand;
        }
    }

XAML では、Binding を Command プロパティに次のように設定します。

 <Button Command="{Binding Path=YourCommand}" .../>
于 2010-12-20T14:43:49.287 に答える
1

おそらく、この記事はあなたが探しているものを説明しています。私も数分前に同じ問題を抱えていました。

http://www.eggheadcafe.com/sample-code/SilverlightWPFandXAML/76e6b583-edb1-4e23-95f6-7ad8510c0f88/pass-command-parameter-to-relaycommand.aspx

于 2010-12-19T15:37:05.343 に答える