如何对非命令MenuItem IsEnabled进行数据绑定以与基于命令的MenuItem保持一致?

时间:2010-08-18 19:32:35

标签: wpf binding

这个menuItem因为它链接到一个命令为我做幕后魔术:

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

我在哪里

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

但我尝试的每一个绑定都没有做任何事情。

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

1 个答案:

答案 0 :(得分:1)

它工作正常可能你忘了设置CanExecute标志或有其他依赖

完整代码

<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>

和班级

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
    }
}