MVVMを使用してSilverlightでコマンドにCommandParameterを渡します
-
11-10-2019 - |
質問
Silverlightを学んで、MVVMを見て指揮を執っています。
わかりました、だから私は基本的なリレーコマンドの実装を見ました:
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では、コマンドを作成する必要がありますが、 RelayCommand
期待しています Action
委任。実装できますか RelayCommand<T>
使用 Action<T>
- もしそうなら、どうすればそれを行うことができますか、そしてそれをどのように使用しますか?
既存のライブラリを使用する前に完全に理解したいので、サードパーティライブラリ(MVVM Lightなど)を使用することを伴わないMVVMを使用して、CommandParametersの実用的な例を教えてください。
ありがとう。
解決
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では、次のようなコマンドプロパティにバインディングを設定します。
<Button Command="{Binding Path=YourCommand}" .../>
他のヒント
たぶん、この記事であなたが探しているものを説明しています。また、ほんの数分前に同じ問題がありました。
所属していません StackOverflow