如何将 MenuItem.Header 绑定到 Window/UserControl 的依赖属性?

4
我可以帮忙翻译这段内容。这是一个关于IT技术的问题,询问如何将MenuItem.Header绑定到父级Window或UserControl的依赖属性。以下是一个简单的示例:

Window1.xaml:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" x:Name="self">
    <Grid>
        <Grid.ContextMenu>
            <ContextMenu>
                <MenuItem Header="{Binding Path=MenuText, ElementName=self}" />
            </ContextMenu>
        </Grid.ContextMenu>
        <TextBlock Text="{Binding Path=MenuText, ElementName=self}"/>
    </Grid>
</Window>

Window1.xaml.cs:

public partial class Window1 : Window {
    public static readonly DependencyProperty MenuTextProperty = DependencyProperty.Register(
        "MenuText", typeof (string), typeof (Window1), new PropertyMetadata("Item 1"));

    public Window1()
    {
        InitializeComponent();
    }

    public string MenuText {
        get { return (string)this.GetValue(MenuTextProperty); }
        set { this.SetValue(MenuTextProperty, value); }
    }
}

在我的情况下,文本块显示为“Item 1”,而上下文菜单则显示为空。我做错了什么?对于我来说,似乎我遇到了WPF数据绑定原则的严重误解。
2个回答

8
您应该在Visual Studio的输出窗口中看到以下内容:

System.Windows.Data Error: 4 : 找不到引用'ElementName=self'的绑定源。BindingExpression:Path=MenuText; DataItem=null; 目标元素是'MenuItem'(名称=''); 目标属性是'Header'(类型为'Object')

这是因为ContextMenu与VisualTree断开连接,您需要以不同的方式进行绑定。
一种方法是通过ContextMenu.PlacementTarget(应该是Grid),您可以使用它的DataContext建立绑定,例如:
<MenuItem Header="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.DataContext.MenuText}"/>

或者在ContextMenu本身中设置DataContext:
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}">
    <MenuItem Header="{Binding Path=MenuText}"/>
</ContextMenu>

如果这不是一个选项(因为Grid的DataContext不能是Window/UserControl),你可以尝试通过Grid的Tag传递Window/UserControl的引用。

<Grid ...
      Tag="{x:Reference self}">
    <Grid.ContextMenu>
        <!-- The DataContext is now bound to PlacementTarget.Tag -->
        <ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.Tag}">
            <MenuItem Header="{Binding Path=MenuText}"/>
        </ContextMenu>
    ...

作为一则旁注:由于这种行为,我倾向于在App.xaml中定义一个帮助器样式,以使所有的上下文菜单“伪继承”它们父元素的数据上下文:
    <!-- Context Menu Helper -->
    <Style TargetType="{x:Type ContextMenu}">
        <Setter Property="DataContext" Value="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}"/>
    </Style>

请问如何通过标记将引用传递给窗口/UserControl? 如果我使用Tag = "{x:Reference self}"语法,我会收到编译错误“在XML命名空间'http://schemas.microsoft.com/winfx/2006/xaml'中不存在'tag'引用”。 我使用VS2008和.NET Framework 3.5。 - s.ermakovich
只存在于.NET 4中,您应该能够使用绑定,例如Tag="{Binding ElementName=self}" - H.B.

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接