Search code examples
c#wpfmenuitemcanexecute

How to get a MenuItem from within its CanExecute handler?


How can I get access to the related MenuItem? It has been created on the fly, so I cannot just use it by a name in the xaml file.

private void menuItem_canExecute(object sender, CanExecuteRoutedEventArgs e)
{
    var snd = sender; // This is the main window
    var orgSource = e.OriginalSource; // This is a RichTextBox;
    var src = e.Source; // This is a UserControl

    // I think I must use the Command, but how?
    RoutedCommand routedCommand = e.Command as RoutedCommand;
}

Solution

  • You can always pass the commanding UI element to a command by binding itself to its CommandParameter property, like

    <MenuItem ... CommandParameter="{Binding RelativeSource={RelativeSource Self}}"/>
    

    Now you can access the MenuItem by the Parameter property of the CanExecuteRoutedEventArgs:

    private void menuItem_canExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        var menuItem = e.Parameter as MenuItem;
        ...
    }