Reputation: 594
With the help of this article, I created TreeView by using WPF with MVVM. Now I want to add different context menu to every items in the one level. A google research allows me to create a same context menu to every items in one level.
So my question Do you have any idea that allow me to create context Menu to every item in the same level with full respect to the architecture MVVM ?
Below the code that allow me to create same context menu to every items in one level:
<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\RedCircle.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\RedCircle.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>
Upvotes: 1
Views: 2025
Reputation: 1291
You add collection of MenuItems to your view model and bind ContextMenu.ItemsSource to it:
Example:
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); }) });
}
}
And in your xaml resources:
<ContextMenu x:Key="TreeViewContextualMenuLevel2" ItemsSource="{Binding ContextMenuItems}" />
So, you could create individual context menu for every item based on conditions you have
Example of RelayCommand can be found here
Hope, it helps
Upvotes: 3