TreeView add different context Menu to every item in the same level, WPF MVVM
在本文的帮助下,我通过将WPF与MVVM一起使用创建了TreeView。现在,我想在一个级别的每个项目中添加不同的上下文菜单。
一项Google研究使我可以为同一级别中的每个项目创建相同的上下文菜单。
所以我的问题是,您有什么想法可以让我在完全尊重MVVM体系结构的情况下为同一级别的每个项目创建上下文菜单吗?
下面的代码使我可以为一个级别中的每个项目创建相同的上下文菜单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <TreeView.Resources> <!-- Begin Context Menu --> <ContextMenu x:Key="TreeViewContextualMenuLevel2"> <MenuItem Command="{Binding AddLevelTwoCommand}" Header="Add"/> </ContextMenu> <ContextMenu x:Key="TreeViewContextualMenuLevel3"> <MenuItem Command="{Binding EditCommand}" Header="Edit" /> <MenuItem Command="{Binding RemoveCommand}" Header="Remove" /> </ContextMenu> <!-- End context Menu --> <!-- Begin Level 1 --> <HierarchicalDataTemplate DataType="{x:Type local:FirstLevelViewModel}" ItemsSource="{Binding Children}"> <StackPanel Orientation="Horizontal"> <Image Width="16" Height="16" Margin="3,0" Source="/Images\ edCircle.png" /> <TextBlock Text="{Binding DefEntity1Name}" /> </StackPanel> </HierarchicalDataTemplate> <!-- End Level 1 --> <!-- Begin Level 2: Root --> <HierarchicalDataTemplate DataType="{x:Type local:SecondLevelViewModel}" ItemsSource="{Binding Children}"> <StackPanel Orientation="Horizontal" ContextMenu="{StaticResource TreeViewContextualMenuLevel2}"> <Image Width="16" Height="16" Margin="3,0" Source="/Images\ edCircle.png" /> <TextBlock Text="{Binding DefEntity2Name}" /> </StackPanel> </HierarchicalDataTemplate> <!-- End Level 2: Root --> <!-- Begin Level 3 --> <DataTemplate DataType="{x:Type local:ThirdLevelViewModel}"> <StackPanel Orientation="Horizontal" ContextMenu="{StaticResource TreeViewContextualMenuLevel3}"> <Image Width="16" Height="16" Margin="3,0" Source="/Images\\GreenCircle.png" /> <TextBlock Text="{Binding ThirdLevelEntityName}" /> </StackPanel> </DataTemplate> <!-- End Level 3 --> </TreeView.Resources> |
您将MenuItems的集合添加到视图模型中,并将ContextMenu.ItemsSource绑定到它:
示例:
1 2 3 4 5 6 7 8 9 10 11 | public class ViewModel { public List<MenuItem> ContextMenuItems { get; set; } public ViewModel() { ContextMenuItems = new List<MenuItem>(); ContextMenuItems .Add(new MenuItem() { Header ="item1", Command = new RelayCommand(() => { MessageBox.Show("Item 1 is clicked","test", MessageBoxButton.OK, MessageBoxImage.Error); }) }); ContextMenuItems.Add(new MenuItem() { Header ="item2", Command = new RelayCommand(() => { MessageBox.Show("Item 2 is clicked","test", MessageBoxButton.OK, MessageBoxImage.Error); }) }); } } |
在您的xaml资源中:
1 | <ContextMenu x:Key="TreeViewContextualMenuLevel2" ItemsSource="{Binding ContextMenuItems}" /> |
因此,您可以根据自己的条件为每个项目创建单独的上下文菜单。
可以在此处找到RelayCommand的示例
希望它有帮助