【问题标题】:Binding contextmenu command in a tree view with hierarchical data template在具有分层数据模板的树视图中绑定上下文菜单命令
【发布时间】:2017-02-03 19:18:29
【问题描述】:

我有一个带有分层数据模板的树视图,我正在尝试为 ContextMenu 设置 DataContext,因此我可以将命令绑定到它。我做过研究,知道 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>

【问题讨论】:

    标签: c# wpf binding treeview command


    【解决方案1】:

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

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

    您需要将父 TreeViewItem 的 Tag 属性绑定到其 DataContext,然后在上下文菜单的分层模板中的某个位置,您应该将其 DataContext 绑定到父控件的 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 2012-11-06
      相关资源
      最近更新 更多