TreeView ContextMenu MVVM Binding

I currently have a UserControl that uses the MVVM model.

This control has a TreeView that displays some elements. I added a HierarchicalDataTemplate for this TreeView and in this template is ContextMenu for the elements.

In the ViewModel, which is the DataContext of the control (named RestoresTreeViewControl), is the command I want to associate with one of the menu items. However, what I did does not seem to work. I get the usual can not find the source for the link binding.

Here is a bit of code for the data file that tried to bind EditDatabaseCommand with one of the menu items.

<HierarchicalDataTemplate DataType="{x:Type model:Database}" > <StackPanel> <TextBlock Text="{Binding Name}" > <TextBlock.ContextMenu> <ContextMenu> <MenuItem Header="Edit" Command="{Binding ElementName=RestoresTreeViewControl, Path=DataContext.EditDatabaseCommand}" /> <MenuItem Header="Delete"/> <Separator/> <MenuItem Header="Test Connection"/> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> </StackPanel> </HierarchicalDataTemplate> 

Here is the ViewModel section where the command is located.

 public ICommand EditDatabaseCommand { get; private set; } 
+4
source share
3 answers

Unfortunately, ContextMenu is not in VisualTree, so it will not see your DataContext. What you can do is something like this (copied here: MVVM binding command to the contextmenu element )

 <Button Height="40" Margin="0,2,0,0" CommandParameter="{Binding Name}" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" Command = "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.ConnectCommand}"> <Button.ContextMenu> <ContextMenu> <MenuItem Header="Remove" CommandParameter="{Binding Name}" Command="{Binding Path=PlacementTarget.Tag.DataContext.RemoveCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/> </ContextMenu> </Button.ContextMenu> 

So just use PlacementTarget.Tag to find the ViewModel.

+3
source

You can try tracking the binding:

  xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase" ... {binding ... diag:PresentationTraceSources.TraceLevel="High"} 

However, it is required that the users (even if it was just themselves) of your control to call each instance of "RestoresTreeViewControl" quite burdensome.

Try:

  {Binding Path=... RelativeSource={ FindAncestor, AncestorType={x:TheRestoresTreeViewControlType}} } 
0
source

This is probably due to the context of inheritance.

See: Associating WPF ContextMenu MenuItem with UserControl Property vs ViewModel Property

0
source

Source: https://habr.com/ru/post/1334068/


All Articles