简体   繁体   English

使用HierarchicalDataTemplate将ContextMenu添加到TreeView

[英]Add ContextMenu to TreeView with HierarchicalDataTemplate

I want to add a contextmenu to a TreeView. 我想将上下文菜单添加到TreeView。 This I can do by the following code: 我可以通过以下代码执行此操作:

<TreeView x:Name="treeView" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding Classes}"
              commandBehaviors:MouseDoubleClick.Command="{Binding TreeMouseDoubleClick}"
              commandBehaviors:MouseDoubleClick.CommandParameter="{Binding ElementName=treeView, Path=SelectedItem}"
              Margin="3,3,3,3" ContextMenu="{Binding ContextMenu, Mode=OneWay}">
...

My TreeView only have two levels. 我的TreeView只有两个级别。 Class and Pupil. 班级和学生。

My problem now is, that I have a HierarchicalDataTemplate for my TreeView and I only want to show the contextMenu if the right-click is on a class-node 我现在的问题是,我的TreeView有一个HierarchicalDataTemplate,并且仅在右键单击类节点时才想显示contextMenu。

This looks like 看起来像

<HierarchicalDataTemplate DataType="{x:Type Entity:Class}" ItemsSource="{Binding Pupils}">
                <Label Content="{Binding Name}"/>
            </HierarchicalDataTemplate>
            <DataTemplate DataType="{x:Type Entity:Pupil}">
                <Label Margin="0">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <Label Grid.Column="0" Content="{Binding Lastname}" Margin="0"/>
                        <Label Grid.Column="1" Content="{Binding Firstname}" Margin="0"/>
                    </Grid>
                </Label>
            </DataTemplate>

How can I solve this? 我该如何解决?

I suggest adding a view-model to wrap your Class type, and creating a property on it for the ContextMenu. 我建议添加一个视图模型来包装您的Class类型,并在其上为ContextMenu创建一个属性。 Instantiate these view-models to wrap each Class type, and change the DataType in your HierarchicalDataTemplate to be the new view-model's type. 实例化这些视图模型以包装每种类类型,并将HierarchicalDataTemplate中的DataType更改为新的视图模型的类型。 Then, the label in your HierarchicalDataTemplate can bind to the ContextMenu property, and you can remove the ContextMenu binding off your TreeView. 然后,您的HierarchicalDataTemplate中的标签可以绑定到ContextMenu属性,并且可以从TreeView删除ContextMenu绑定。 It will show on Class objects, but not on Pupil objects. 它将显示在Class对象上,而不显示在Pupil对象上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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