我正在学习Silverlight并关注MVVM和命令。
好的,所以我看到了基本的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中,我需要创建命令,但RelayCommand
期待Action
代理。我可以使用RelayCommand<T>
实施Action<T>
- 如果是,我该怎么做以及如何使用它?
任何人都可以给我任何关于MVVM的CommandParameters的实际例子,它们不涉及使用第三方库(例如MVVM Light),因为我想在使用现有库之前完全理解它。
感谢。
答案 0 :(得分: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 to Command Property,如:
<Button Command="{Binding Path=YourCommand}" .../>
答案 1 :(得分:1)