我可以帮忙翻译这段内容。这是一个关于IT技术的问题,询问如何将MenuItem.Header绑定到父级Window或UserControl的依赖属性。以下是一个简单的示例:
在我的情况下,文本块显示为“Item 1”,而上下文菜单则显示为空。我做错了什么?对于我来说,似乎我遇到了WPF数据绑定原则的严重误解。
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数据绑定原则的严重误解。
Tag="{Binding ElementName=self}"
。 - H.B.