[英]ContextMenu Binding from a TreeView
我有一個簡單的任務,將上下文菜單綁定到TreeView中的項目。 如果我靜態定義上下文菜單沒問題。 但是,如果我想將上下文菜單綁定到我的“根”數據上下文,事情就會開始中斷。 到目前為止,我無法找到將Context菜單綁定到TreeView使用的原始DataContext的正確方法。 讓這個工作需要什么樣的綁定魔法? 此綁定不起作用:
<MenuItem Name="Name" Header="{Binding Path=DataContext.ContextMenuName, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeView}}}" />
以下是完整示例:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:ui="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView ItemsSource="{Binding Path=Persons, Mode=OneTime}" Name="cTree">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate>
<TextBox Text="{Binding Mode=OneWay}">
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Name="Name" Header="{Binding Path=DataContext.ContextMenuName, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeView}}}" />
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
public partial class MainWindow : Window
{
public string[] Persons
{
get { return new string[] { "Alois", "Kraus", "Joe", "xxxx" }; }
}
public string ContextMenuName
{
get;
set;
}
public MainWindow()
{
ContextMenuName = "This is the data bound menu name";
InitializeComponent();
this.DataContext = this;
}
}
基本上我想綁定主窗體的屬性ContextMenuName(實際上是我的ViewModel中的命令)。 由於TreeView將其子項重新綁定到Persons(字符串以保持簡單),因此我無法從中獲取根DataContext。 到目前為止,我從來沒有找到任何應該解決問題的Ancestor(TreeView或MainWindow)? 我在這做錯了什么?
ContextMenu
與應用它的控件不在同一個可視樹中。 所以FindAncestor
將無法訪問TreeView,因為它不是ContextMenu的祖先。
此外, ElementName
在此處不起作用,因為它還需要兩個控件位於同一個Visual樹中。
你可以使用x:Reference ,它允許綁定,即使它們不在同一個可視樹中:
<MenuItem Name="Name"
Header="{Binding Path=DataContext.ContextMenuName,
Source={x:Reference cTree}}" />
您是否嘗試通過ElementName=cTree
而不是RelativeSource={...}
綁定?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.