I have a TreeView whose itemsource is a collection of my Model class. I have added a context menu on the treeView. Since the commands of the contextMenu should be in the visual tree, so I had to place them in my Model class. Which is wrong (Binding directory to the Model).
How can I Bind my context menu's Command to my ViewModel rather than Model?
Here is my XAML code for TreeView.
<TreeView ItemsSource="{Binding DigSource}" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
<TreeView.ItemContainerStyle >
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu >
<MenuItem Header="Edit" CommandParameter="{Binding }"
Command="{Binding Path=PlacementTarget.Tag.DataContext.MyCommand,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SingleDig}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
</StackPanel>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate DataType="{x:Type dt:MultiDig}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
and ViewModel's Icommand Property is
private ICommand _editMenuCommand;
/// <summary>
/// Edit command
/// </summary>
public ICommand EditMenuCommand { get { return _editMenuCommand ?? (_editMenuCommand = new RelayCommand(EditMenu)); } }
/// <summary>
/// Edit menu
/// </summary>
public void EditMenu()
{
MessageBox.Show("Edit me");
}
Thanks in advance.