Click here to Skip to main content
15,887,346 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My English is bad, so I don't know if I can make it clear, sorry about that.
And I really don't know how to explain it when trying to do some research.

Currently, I have a page which is a UserConstrol called "ToolPathPage", and it contains another UserControl called "ToolPathDataControl" which contains nothing but a DataGrid.

Now I want to bind a Command in the ToolPathPageViewModel to a MenuItem in ToolPathDataControl.xaml.

What I have tried:

XML
<DataGrid.ContextMenu>
    <ContextMenu >
        <MenuItem Header="Clear" Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ToolPathPage},AncestorLevel= 1}, Path=DataContext.(viewModel:ToolPathPageViewModel.Clear_AllCommand)}"/>
    </ContextMenu>
</DataGrid.ContextMenu>

In the Output window it says:
Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='mTracker.ToolPathPage', AncestorLevel='1''. BindingExpression:Path=DataContext.(0); DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')
Posted
Updated 2-Nov-18 17:07pm
v3
Comments
Graeme_Grant 31-Oct-18 21:45pm    
"BindingExpression:Path=DataContext.(0); DataItem=null;" - can't find the DataContext that you are looking for...
0x222fe 31-Oct-18 21:58pm    
Thanks for the reply, but I did set the DataContext of the ToolPathPage to ToolPathPageViewModel.
And does this means the ToolPathPage is successfully found as an ancestor?
Graeme_Grant 31-Oct-18 22:08pm    
You can use the XAML inspector in VS2017 to check ;)
Richard Deeming 2-Nov-18 10:23am    
The context menu is not part of the visual tree, so a "find ancestor" binding won't work.

You might be able to find a workaround based on this article:
WPF: ContextMenu Strikes Again. DataContext Not Updated[^]
0x222fe 2-Nov-18 22:58pm    
It works, thanks a lot!

1 solution

Thanks to @RichardDeeming, I got my final solution:
XML
<DataGrid Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ToolPathPage}},Path=DataContext.(viewModel:ToolPathPageViewModel.Clear_AllCommand)}">
    <DataGrid.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Clear" Command="{Binding PlacementTarget.Tag,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}"/>
        </ContextMenu>
    </DataGrid.ContextMenu>
</DataGrid>
 
Share this answer
 
v3
Comments
awsnap 14-Jun-20 22:32pm    
Yes, yes, yes. This is the only answer I could find that held to MVVM and addressed the ContextMenu Visual Tree separation.

In my case DataGrid was actually StackPanel. I also just used DataContext.TheCommand.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900