简体   繁体   中英

Context menu on Treeview does not open on selected item

I have a treeview with a context menu and I am using an converter to manage it. I do not want the menu to open on items and just want it to open on nodes.

<BooleanToVisibilityConverter x:Key="VisibilityConverter" />
  <ContextMenu x:Key="AddNew" Name="PopMnu" Visibility="{Binding IsFolder,Converter={StaticResource VisibilityConverter}}">
    <MenuItem Header="New Symbol..." Click="AddSymbolMenu_Click"/>
    <MenuItem Header="New Folder..." Click="NewFolderItem_Click"/>
  </ContextMenu> 

  <Style TargetType="{x:Type TreeViewItem}">
      <Setter Property="ContextMenu" Value="{StaticResource AddNew}"/>
  </Style>

When I right click on an item, no menu comes up but now when I right click on a node, the menu comes up but on the location of the item previously right clicked. Also the menu does not dismiss unless you right click again on any item. Any help please?

As Krishna's comment suggested, a solution would be to have a view model for a folder and one for an item

public class Folder : ViewModelBase { }   
public class Item : ViewModelBase { }   

Then you can define a DataTemplate for each, one containing a context menu the other without.

 <TreeView Name="SymbolsTreeView" ItemsSource="{Binding Items}">
        <TreeView.Resources>

            <HierarchicalDataTemplate DataType="{x:Type local:Folder}" ItemsSource="{Binding Items}">
                <Grid Background="Red">
                        <Grid.ContextMenu>
                        <ContextMenu>
                        </ContextMenu>
                    </Grid.ContextMenu>
                    <TextBlock Text="{Binding Name}"/>
                </Grid>
            </HierarchicalDataTemplate>

            <DataTemplate DataType="{x:Type local:Item}" >
                <Grid >
                    <TextBlock Text="{Binding Name}"/>
                </Grid>
            </DataTemplate>

        </TreeView.Resources>
    </TreeView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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