Wpf 如何绑定到ItemTemplate中的父UIElement?
我试图绑定到MainWindow的一个属性,但是是从Wpf 如何绑定到ItemTemplate中的父UIElement?,wpf,binding,contextmenu,itemtemplate,uielement,Wpf,Binding,Contextmenu,Itemtemplate,Uielement,我试图绑定到MainWindow的一个属性,但是是从DataTemplate中的ContextMenu绑定的。我怎样才能做到这一点 我不能使用ElementName,因为上下文菜单不是可视化树的一部分 我不能使用PlacementTarget,因为这将提供由DataTemplate <Window x:Class="WpfApplication24.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr
DataTemplate
中的ContextMenu
绑定的。我怎样才能做到这一点
- 我不能使用
,因为上下文菜单不是可视化树的一部分ElementName
- 我不能使用
,因为这将提供由PlacementTarget
DataTemplate
<Window x:Class="WpfApplication24.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ItemsControl ItemsSource="{Binding Data}"> <ItemsControl.ItemTemplate> <DataTemplate> <Border Padding="5" CornerRadius="10" BorderThickness="1" BorderBrush="Red"> <Border.ContextMenu> <ContextMenu ItemsSource="{Binding <I want to bind to a property of MainWindow here>}"/> </Border.ContextMenu> <TextBlock Text="{Binding}"/> </Border> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>
边框的标记中,然后使用PlacementTarget.Tag
<DataTemplate>
<Border Padding="5" CornerRadius="10" BorderThickness="1" BorderBrush="Red"
Tag="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType=Window}}">
<Border.ContextMenu>
<ContextMenu ItemsSource="{Binding PlacementTarget.Tag.PropertyName,
RelativeSource={RelativeSource Self}}"/>
</Border.ContextMenu>
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
我使用的是一个简单的自定义控件包装
,例如MyContextMenu
…只需要一行代码,就像
public class MyContextMenu : ContextMenu
{
public override void EndInit()
{
base.EndInit();
NameScope.SetNameScope(this, NameScope.GetNameScope(App.Current.MainWindow));
}
}
…并使用它而不是ContextMenu
这总是“作用域”到main窗口,这可能并不总是最佳的-但您可以使用ElementName
等
2) 另一个选项是使用NameScope.NameScope=“{StaticResource myNameScope}”
NameScope.NameScope
似乎是一个最佳解决方案-但是,您无法从中绑定(而且绑定“太晚了”。
但是您可以使用{StaticResource…}
-并创建一个围绕MainWindow作用域的类。
类似,但我发现上面的“破坏性”比较小(您几乎可以编写通常编写的代码)
有关更多详细信息,请查看此答案(以及更多想法)