I need the command I am executing on a datagrids context menu to know which column was clicked on.
XAML
<DataGrid x:Name="dataGrid" ItemsSource="{Binding Table}" ContextMenuOpening="DataGrid_ContextMenuOpening">
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Add Column" Command="{Binding AddColumn}"/>
<MenuItem Header="Remove Column" Command="{Binding RemoveColumn}"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
Code behind:
private void DataGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var current = e.OriginalSource as DependencyObject;
while(current != null && !(current is DataGridCell))
{
current = VisualTreeHelper.GetParent(current);
}
var cell = current as DataGridCell;
foreach (var item in dataGrid.ContextMenu.Items.OfType<MenuItem>())
{
item.CommandParameter = cell.Column.DisplayIndex;
(item.Command as DelegateCommand<object>)?.RaiseCanExecuteChanged();
}
}
I'm having to break MVVM by having the view tell the VM command that its execution has changed because the command binding doesn't seem to refresh on the parameter changing. Is there a better way to do this?