I am cooking up DataGridTemplateColumns programmatically via
DataTemplate dtStringTemplate = (DataTemplate)XamlReader.Load(sr, pc);
dataGridTemplateColumn.CellTemplate = dtStringTemplate;
I tried adding the ContextMenu to the DataGrid, but any editable cells used their own context menu.
So far, this post has gotten me as far as getting the TextBox context menu to appear as expected: How to add a ContextMenu in the WPF DataGridColumn in MVVM?
Using the post mentioned above as a guide, I have created the Style and the ContextMenu in App.xaml; when I right-click on the Cell in the DataGrid, my context menu appears. However, I can't get the associated command to fire, and I suspect the binding is not right. Here's the xaml in App.xaml:
<ContextMenu x:Key="DataGridContextMenu">
<MenuItem Header="MenuItem One" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.CmdMenuItemOne}" />
<MenuItem Header="MenuItem Two" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.CmdMenuItemOne}" />
</ContextMenu>
The DataContext for the DataGrid is MyViewModel; MyViewModel has a public DelegateCommand named CmdMenuItemOne.
Unfortunately, CmdMenuItemOne is never called.
What am I misunderstanding in the binding? Thanks ...
since the fact that a ContextMenu isn't a part of a DataGrid's visual tree, we cannot access property defined in the DataGrid's DataContext. But we can do the next workaround to do that.
style code (should be in App.xaml)
attached property code
helper code
Regards.