Search code examples
c#wpfcode-behindrouted-commands

Why RoutedCommand doesnt work on that code?


The 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: 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");
    }
}

The XAML, it's a test form, so there is only that button:

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

When I click the "Test" button, nothing happens, No CanExecute, no PreviewExecuted, no Executed...

What's wrong with that code?


Solution

  • In your code you create CommandBinding which says how to handle particular command (TestRoutedCommand), but you don't execute this command (unless you uncomment your line). If you want to execute it on button click, just do:

    buttonTest.Command = TestRoutedCommand;