代码之家  ›  专栏  ›  技术社区  ›  Maslow

如何将非命令菜单项与基于命令的菜单项进行数据绑定以保持一致?

  •  1
  • Maslow  · 技术社区  · 14 年前

    这个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 回复  |  直到 14 年前
        1
  •  1
  •   Lukasz Madon    14 年前

    它可以正常工作,也许你忘记设置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
        }
    }