Maslow
Maslow

Reputation: 18746

How can I databind a non-command MenuItem IsEnabled to stay consistent with a command based MenuItem?

This menuItem because it's linked to a command does the magic behind the scenes for me:

 <MenuItem Name="mnuOpen"  Command="Open"/>

where I have

    <Window.CommandBindings>
    <CommandBinding Command="Open"
                    Executed="CommandBinding_Open_Executed"
                    CanExecute="CommandBinding_ProjectSelected"/>
    </Window.CommandBindings>

but every binding I've tried has failed to do anything.

<MenuItem Name="mnuExplorer" Click="mnuExplorer_Click" Header="Open Containing Folder" IsEnabled="{Binding ElementName=mnuOpen, Path=IsEnabled}" />

Upvotes: 1

Views: 718

Answers (1)

Lukasz Madon
Lukasz Madon

Reputation: 14994

It works fine maybe you forgot to set CanExecute flag or have other dependency

full code

<Window x:Class="MenuBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.CommandBindings>
    <CommandBinding Command="Open"
                Executed="CommandBinding_Executed"
                CanExecute="CommandBinding_CanExecute"/>
</Window.CommandBindings>
<Grid>
    <Menu>
        <MenuItem Name="mnuOpen"  Command="Open" IsEnabled="False" />
        <MenuItem Name="mnuExplorer" Header="Open Containing Folder" IsEnabled="{Binding ElementName=mnuOpen, Path=IsEnabled}" />
    </Menu>
</Grid>

and class

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

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

    private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true; //define if command can be executed
    }
}

Upvotes: 1

Related Questions