为什么 RoutedCommand 不适用于该代码?

Why RoutedCommand doesnt work on that code?

代码:

public partial class MainWindow : Window
{
    public static readonly RoutedCommand TestRoutedCommand = new RoutedCommand();

    public MainWindow()
    {
        InitializeComponent();


        CommandBinding testCommandBinding = new CommandBinding(TestRoutedCommand, Test_Executed, Test_CanExecute);
        testCommandBinding.PreviewExecuted += Test_PreviewExecuted;

        buttonTest.CommandBindings.Add(testCommandBinding);

        // WHEN I UNCOMMENT THAT LINE, ONLY THE "Preview" MESSAGEBOX IS SHOWN
        //TestRoutedCommand.Execute(null, buttonTest);    
        // Ok, I understood that part here: 
    }

    private void Test_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    private void Test_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        MessageBox.Show("Preview");
    }

    private void Test_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        MessageBox.Show("Executed");
    }
}

XAML,这是一个测试表单,所以只有那个按钮:

<Button x:Name="buttonTest" Width="30" Height="30">Test</Button>

当我点击 "Test" 按钮时,没有任何反应,没有 CanExecute,没有 PreviewExecuted,没有 Executed...

该代码有什么问题?

在您的代码中,您创建了 CommandBinding,它说明了如何处理特定命令 (TestRoutedCommand),但您不执行此命令(除非您取消注释您的行)。如果你想在按钮点击时执行它,只需执行:

buttonTest.Command = TestRoutedCommand;