如何使用命令执行WPF控制方法?
我已经创建了一个 RelayCommand 类和命令类,其中我试图通过lambda表达式传递的方法RichTextBox 类是RelayCommand的结构函数。
在lambda中我将一个参数转换为目标 RichTextBox ,然后调用方法Clear()。但是,当我尝试单击绑定到该命令的MenuItem时,它会抛出 RefferenceNullException ,即传递给lambda并尝试转换为RichTextBox的参数为null。
如何正确地做这种操作?
RelayCommand代码:
class RelayCommand : ICommand
{
private readonly Action<object> _Execute;
private readonly Func<object, bool> _CanExecute;
public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
{
if (execute == null) throw new ArgumentNullException("execute");
_Execute = execute;
_CanExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _CanExecute == null ? true : _CanExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add
{
if (_CanExecute != null) CommandManager.RequerySuggested += value;
}
remove
{
if (_CanExecute != null) CommandManager.RequerySuggested -= value;
}
}
public void Execute(object parameter)
{
_Execute(parameter);
}
}
命令代码:
class Commands
{
private ICommand _NewFileCommand;
public ICommand NewFileCommand
{
get
{
if (_NewFileCommand == null)
{
_NewFileCommand = new RelayCommand(
argument => { (argument as RichTextBox).Document.Blocks.Clear(); },
// argument => (argument as RichTextBox).Document != null
argument => true
);
}
return _NewFileCommand;
}
}
}
MainWindow.xaml中的窗口资源和DataContext设置
<Window.Resources>
<local:Commands x:Key="commandsClass" />
</Window.Resources>
<Window.DataContext>
<local:Commands />
</Window.DataContext>
MainWindow.xaml中的MenuItem设置
<MenuItem Header="_New" Command="{Binding NewFileCommand}" />
答案 0 :(得分:1)
更新绑定以将RichTextBox
作为命令参数发送到视图模型。
<MenuItem Header="_New" Command="{Binding NewFileCommand}"
CommandParameter="{Binding ElementName=nameOfYourRichTextBox}/>