wpf - 命令,上下文菜单

发布于 2024-09-28 18:32:56 字数 52 浏览 0 评论 0原文

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

How can I put the ContextMenu in a resource xaml file and bind it's commands to my current window's commands ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哆啦不做梦 2024-10-05 18:32:56
Command="{Binding SomeCommand}"

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

EG

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

Command="{Binding SomeCommand}"

It will use your current controls DataContext which should hold a command property "SomeCommand"

E.G.

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

And in my ViewModel I would have the following property

    public ICommand TestCommand { get; set; }

And in my View.xaml

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

Therefore the buttons DataContext is my ViewModel, therefore the SomeContextMenu which is in a ResourceDictionary in a external file binds to the same DataContext as the button, and therefore finds the SomeCommand within the ViewModel.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文