如何使用 Command 调用 WPF 控件的方法?

How to call a method of WPF control using Command?

如何使用命令执行 WPF 控件的方法?

我创建了一个 RelayCommand class 和 Commands class,我在其中尝试通过 lambda 表达式,RichTextBox class 的方法传递给 RelayCommand 的 cunstructor。

在 lambda 内部,我将参数转换为目标 RichTextBox,然后调用方法 Clear()。但是,当我尝试单击绑定到该命令的 MenuItem 时,它会抛出 RefferenceNullException,传递给 lambda 并试图转换为 RichTextBox 的参数为 null。

如何正确的进行这种操作??

中继命令代码:

       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;
               }
           }
       }

Window 资源和 MainWindow.xaml

内的 DataContext 设置
<Window.Resources>
    <local:Commands x:Key="commandsClass" />
</Window.Resources>
<Window.DataContext>
    <local:Commands />
</Window.DataContext>

MenuItem里面的设置MainWindow.xaml

<MenuItem Header="_New" Command="{Binding NewFileCommand}" />

更新您的绑定以将 RichTextBox 作为命令参数发送到视图模型。

<MenuItem Header="_New" Command="{Binding NewFileCommand}" 
    CommandParameter="{Binding ElementName=nameOfYourRichTextBox}/>