【问题标题】:wpf - commands , contextmenuwpf - 命令,上下文菜单
【发布时间】:2010-10-25 12:24:46
【问题描述】:

如何将 ContextMenu 放入资源 xaml 文件并将其命令绑定到当前窗口的命令?

【问题讨论】:

    标签: wpf contextmenu command


    【解决方案1】:
    Command="{Binding SomeCommand}"
    

    它将使用您当前的控件 DataContext,该控件应包含命令属性“SomeCommand

    例如

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <ContextMenu x:Key="SomeContextMenu">
            <MenuItem Header="Test Item" Command="{Binding TestCommand}" />
        </ContextMenu>
    </ResourceDictionary>
    

    在我的 ViewModel 中,我将拥有以下属性

        public ICommand TestCommand { get; set; }
    

    在我的 View.xaml 中

    <Button ContextMenu="{StaticResource SomeContextMenu}">Test Button</Button>
    

    因此按钮 DataContext 是我的 ViewModel,因此外部文件中 ResourceDictionary 中的 SomeContextMenu 与按钮绑定到相同的 DataContext,因此在 ViewModel 中找到 SomeCommand。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多