简体   繁体   English

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

[英]How to bind a dependency property to a window resource in WPF?

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. 我想将MenuItem.Header绑定到窗口上名为MenuItemHeader的依赖项属性。 What should {??} be and what should the code behind in the window class look like? {??}应该是什么,并且窗口类中的代码应该是什么样?

You could name the window and reference it 您可以命名窗口并引用它

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

MyDp being the property. MyDp是属性。 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 ) (我将使用Sourcex:Reference因为ElementName通常在诸如ContextMenus断开连接的地方不起作用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM