Click here to Skip to main content
15,881,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#, wpf problem:

I have a data grid with a context menu. On the `previewmouserightbuttonup` event on the `datagrid`, I set the `contextmenu` placement target to the `datagrid`, set the `contextmenu` datacontext to the view model, and open the context menu.

Everything works when selected index of the data grid is >= 0, but when `selectedindex` of the datagrid (the sender of the mouse event) is -1 I receive a `NULL reference exception` for the context menu.

How do I open the `contextmenu` when selectedindex is -1.

What I have tried:

Codebehind
void Datagrid_PreviewMouseRightButtonUp(object sender, MouseEventArgs e)
      {
       var datagrid = sender as DataGrid;
       datagrid.ContextMenu.DataContext = this.DataContext;
       datagrid.ContextMenu.PlacementTarget = datagrid;
       datagrid.ContextMenu.IsOpen = true;
       e.Handled = true;
       }


XAML

I have the following set on the datagrid to handle the PreviewMouseRightButtonUp event:

PreviewMouseRightButtonUp = "Datagrid_PreviewMouseRightButtonUp"
Posted

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