c# - 在具有分层数据模板的 TreeView 中绑定(bind)上下文菜单命令

标签 c# wpf binding treeview command

我有一个带有分层数据模板的 TreeView ,我正在尝试为 ContextMenu 设置 DataContext,因此我可以将命令绑定(bind)到它。我做过研究,知道 ContextMenu 不会继承其父项的 DataContext。我试着关注这些帖子:How to set the RelativeSource in a DataTemplate that is nested in a HierarchicalDataTemplate?

How to bind to the DataContext of a HierarchicalDataTemplate from its ItemTemplate XAML?但仍然无法正常工作。任何帮助,将不胜感激。这是我的示例代码:

<TreeView.Resources>  
    <HierarchicalDataTemplate DataType="{x:Type viewModels:SiteViewModel}" ItemsSource="{Binding Children}">
        <StackPanel Orientation="Horizontal">
            <StackPanel.Resources>
            </StackPanel.Resources>
            <Image Width="16" Height="16" Margin="3,0"  />
            <TextBlock Text="{Binding SiteName}" />
        </StackPanel>
    </HierarchicalDataTemplate>


    <HierarchicalDataTemplate DataType="{x:Type viewModels:LevelViewModel}" ItemsSource="{Binding Children}" >
        <StackPanel Orientation="Horizontal"  >
            <Image Width="16" Height="16" Margin="3,0"  />
            <TextBlock Text="{Binding LevelName}"  >
                <TextBlock.ContextMenu >
                <ContextMenu>
                    <MenuItem Header="Test" Command="{Binding ?????????" CommandParameter="{Binding}"/>
                </ContextMenu>
                </TextBlock.ContextMenu>
            </TextBlock>
        </StackPanel>
    </HierarchicalDataTemplate>

最佳答案

解决方法之一: 就我而言,我有类似的事情:

<DataTemplate DataType="...">
                <TreeView>
                    <TreeViewItem Tag="{Binding ElementName=LocalControl, Path=DataContext}"
                                  Header="{Binding ...}"
                                  ContextMenu="{StaticResource ...}">
                        ...
                    </TreeViewItem>
                </TreeView>
</DataTemplate>

您需要将父级 TreeViewItem 的 Tag 属性绑定(bind)到它的 DataContext,然后在上下文菜单的分层模板中的某处,您应该将其 DataContext 绑定(bind)到父级控件的 Tag:

<ContextMenu x:Key="CyclogramFolderContextMenu"
                         DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                <TextBlock Text="Do something" >
                    <TextBlock.InputBindings>
                        <MouseBinding Command="{Binding Path=(viewModels:someViewModel.SomeCommand)}" MouseAction="LeftClick" />
                    </TextBlock.InputBindings>
                </TextBlock>
</ContextMenu>

关于c# - 在具有分层数据模板的 TreeView 中绑定(bind)上下文菜单命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39702961/

相关文章:

c# - 在 C# 中为大文件创建校验和的最快方法是什么

c# - 如何允许非授权用户访问 get 方法

c# - MongoDB全文搜索

c# - ApplicationSettingsBase ConfigurationErrorsException 多个程序集

wpf - 从 View 模型中刷新 View 上的数据网格

backbone.js - 如何从主干中的另一个 View 将事件绑定(bind)到元素上

c# - 突出显示 Asp.net 图表控件系列中的一列

c# - 如何在不使用PrinterSettings的情况下更改打印机的纸张尺寸?

c# - 我如何在 WPF 应用程序中全局设置文化?

php - mysql中的绑定(bind)参数