Retrieving the right DataContext for Commands in ContextMenu of TreeViewItem

Sep 26, 2013 at 8:30 PM
Hi,

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: https://catel.codeplex.com/discussions/249731

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">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="elements:UniqueIdentifier" ItemsSource="{Binding}">
                    <TextBlock Text="{Binding Path=Name}">
                        <TextBlock.ContextMenu>
                            <ContextMenu>
                                <MenuItem Header="New" Command="{Binding NewUniqueIdentifierCommand}"/>
                                <MenuItem Header="Delete" Command="{Binding DeleteUniqueIdentifierCommand}"/>
                            </ContextMenu>
                        </TextBlock.ContextMenu>
                    </TextBlock>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
....
Any ideas?
Thanks in advance!
Coordinator
Sep 26, 2013 at 9: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 9: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')
Coordinator
Sep 26, 2013 at 9:25 PM
That's weird. Can you create a very small repro and upload it here:

https://catelproject.atlassian.net/secure/Dashboard.jspa

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

Great! That one worked for me!

Thanks alot!