Enable or Disable WPF DataGrid Context Menu Item

Published on Monday, May 13, 2019

Here is an example of how to set WPF DataGrid Context Menu items Enable/Disable status, using Context Menu Opening event.

How to Enable or Disable WPF DataGrid Context Menu Item

private void myDataGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    try
    {
        FrameworkElement element = e.Source as FrameworkElement;
        ContextMenu contextMenu = element.ContextMenu;
        if (contextMenu != null)
        {
            if (this.myDataGrid.SelectedItems.Count >= 1)
            {
                ((MenuItem)(((ContextMenu)contextMenu).Items[0])).IsEnabled = !((DGRowItem)this.myDataGrid.SelectedItem).Enabled;  //enable
                ((MenuItem)(((ContextMenu)contextMenu).Items[1])).IsEnabled = ((DGRowItem)this.myDataGrid.SelectedItem).Enabled;  //disable
                mnuEnable.IsEnabled = !((DGRowItem)this.myDataGrid.SelectedItem).Enabled;  //enable
                mnuDisable.IsEnabled = ((DGRowItem)this.myDataGrid.SelectedItem).Enabled;  //disable
            }
            else
            {
                mnuEnable.IsEnabled = false;
                mnuDisable.IsEnabled = false;
            }

            mnuDel.IsEnabled = (this.myDataGrid.SelectedIndex != -1);
            mnuRunNow.IsEnabled = (this.myDataGrid.SelectedIndex != -1);
            mnuFindinMap.IsEnabled = (this.myDataGrid.SelectedIndex != -1);
            mnuFindAndRun.IsEnabled = (this.myDataGrid.SelectedIndex != -1);
        }
    }
    catch (Exception)
    {
        throw;
    }
}

public class DGRowItem
{
    // ...
}