如何将依赖属性绑定到 WPF 中的窗口资源?

发布于 2025-01-05 21:04:09 字数 374 浏览 3 评论 0原文

假设我有一个上下文菜单作为窗口资源:

<Window.Resources>
    <ContextMenu 
        x:Shared="false"
        x:Key="ContextMenu">
        <MenuItem Header="{??}" />
    </ContextMenu>
</Window.Resources>

并且我想将 MenuItem.Header 绑定到窗口上名为 MenuItemHeader 的依赖属性。 {??} 应该是什么?窗口类后面的代码应该是什么样子?

Suppose I have a context menu as a window resource:

<Window.Resources>
    <ContextMenu 
        x:Shared="false"
        x:Key="ContextMenu">
        <MenuItem Header="{??}" />
    </ContextMenu>
</Window.Resources>

And I want to bind MenuItem.Header to a dependency property called MenuItemHeader on the window. What should {??} be and what should the code behind in the window class look like?

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

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

发布评论

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

评论(1

蓝咒 2025-01-12 21:04:09

您可以命名该窗口并引用它的

<Window Name="Window" ...>
<MenuItem Header="{Binding MyDp, Source={x:Reference Window}}"...>

MyDp 作为属性。如果您不知道如何定义依赖项属性,请阅读概述

(我会使用 Sourcex:引用ElementName 通常在诸如 ContextMenus 这样的断开连接的地方不起作用)

You could name the window and reference it

<Window Name="Window" ...>
<MenuItem Header="{Binding MyDp, Source={x:Reference Window}}"...>

MyDp being the property. If you don't know how to define a dependency property read the overview.

(I would use Source and x:Reference as ElementName usually does not work in disconnected places like ContextMenus)

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