【问题标题】:Why RoutedCommand doesnt work on that code?为什么 RoutedCommand 不适用于该代码?
【发布时间】:2016-04-18 20:06:29
【问题描述】:

代码:

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: http://stackoverflow.com/a/4877259/48729
    }

    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>

当我点击“测试”按钮时,什么也没有发生,没有 CanExecute,没有 PreviewExecuted,没有 Executed...

那段代码有什么问题?

【问题讨论】:

    标签: c# wpf code-behind routed-commands


    【解决方案1】:

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

    buttonTest.Command = TestRoutedCommand;
    

    【讨论】:

    • 难以置信!我以为 buttonTest.CommandBindings.Add(testCommandBinding);够了...谢谢!
    猜你喜欢
    • 2015-07-18
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多