Retrieving the right DataContext for Commands in ContextMenu of TreeViewItem

Sep 26, 2013 at 9:30 PM

I'm trying to call a command. The command is part of a ContextMenu, which is defined within an ItemTemplate/HierarchicalDataTemplate of a TreeView.
I assume, that the command doesn't get called, because of a wrong DataContext.

There are some approaches to this problem on the web, even one from GeertVanHorrik like here:

But I can't get it to work.
Here's the code without any fancy binding stuff.
        <TreeView DockPanel.Dock="Left" ItemsSource="{Binding UniqueIdentifiers}" MinWidth="150" x:Name="UniqueIdentifierTreeView">
                <HierarchicalDataTemplate DataType="elements:UniqueIdentifier" ItemsSource="{Binding}">
                    <TextBlock Text="{Binding Path=Name}">
                                <MenuItem Header="New" Command="{Binding NewUniqueIdentifierCommand}"/>
                                <MenuItem Header="Delete" Command="{Binding DeleteUniqueIdentifierCommand}"/>
Any ideas?
Thanks in advance!
Sep 26, 2013 at 10:12 PM
A simple fix would be:
<MenuItem Header="New" Command="{Binding ElementName=UniqueIdentifierTreeView, Path=DataContext.NewUniqueIdentifierCommand}"/>
The datacontext of the treview control is the view model.
Sep 26, 2013 at 10:21 PM
Thanks for the fast response!

I already tried this, without any success. The command is not called.

The Output shows the following:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=UniqueIdentifierTreeView'. BindingExpression:Path=DataContext.NewUniqueIdentifierCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')
Sep 26, 2013 at 10:25 PM
That's weird. Can you create a very small repro and upload it here:

It's easier to test with code and then I can fix it in a few minutes.
Sep 26, 2013 at 11:32 PM
Sep 26, 2013 at 11:46 PM
You got an answer.
Sep 27, 2013 at 1:00 PM

Great! That one worked for me!

Thanks alot!