繁体   English   中英

ContextMenu从TreeView绑定

[英]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.

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