Search code examples
c#wpftabitemcommandbinding

WPF ComamndBinding Help on MenuItem


New to WPF...was reading this WPF Routed Command with Bindings per-Tab and am close to getting it working.

The MenuItem is disabled until my RuleTab (tabitem) is selected but rather than pop my Find Dialog it shows System.Windows.Input.CommandBinding on the menu. What am I doing wrong?

XAML:

<MenuItem Header="_Find..." IsEnabled="{Binding ElementName=RuleTab, Path=IsSelected}" >
                    <CommandBinding Command="Find" Executed="ExecuteFind" CanExecute="Find_CanExecute" ></CommandBinding>
                </MenuItem>

Code-Behind:

       private void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
    {
        // Initiate FindDialog
        FindDialog dlg = new FindDialog(this.RuleText);

        // Configure the dialog box
        dlg.Owner = this;
        dlg.TextFound += new TextFoundEventHandler(dlg_TextFound);

        // Open the dialog box modally
        dlg.Show();
    }

    void dlg_TextFound(object sender, EventArgs e)
    {
        // Get the find dialog box that raised the event
        FindDialog dlg = (FindDialog)sender;

        // Get find results and select found text
        this.RuleText.Select(dlg.Index, dlg.Length);
        this.RuleText.Focus();
    }

    private void Find_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = RuleTab.IsSelected;
    }

Any suggestions would be greatly appreciated!

Figured it out! Thanks to those responded. All I had to do was move my commandbinding to:

<Window.CommandBindings>
<CommandBinding Command="Find" Executed="ExecuteFind" CanExecute="Find_CanExecute" ></CommandBinding>
</Window.CommandBindings>

Then reference Command=Find in my MenuItem.


Solution

  • You'll find you need to add the CommandBinding to the TabItem (as per the linked sample). Then to bind your MenuItem you should use the Command property, possibly along with a CommandParameter and CommandTarget (pointing back at the TabItem I would expect).

    For example, I have a MenuItem in a ContextMenu and I want the command to fire on the context (placement target) of the ContextMenu:

    <MenuItem Header="View" 
              ToolTip="Open the Member Central view for this member"
              Command="{x:Static local:Commands.CustomerViewed}" 
              CommandParameter="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" 
              CommandTarget="{Binding Path=PlacementTarget, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"
    />