Search code examples
c#wpfdatagrid

How to retrieve DataRow from DataRow.ContextMenu event


How can a bind DataRow to the Tag property of the ContextMenu.MenuItem associated with that row? Here is what I have so far:

<DataGrid.Resources>
    <ContextMenu x:Key="RowContextMenu">
        <ContextMenu.Items>
            <!--This line doesnot work-->
            <MenuItem Header="GoToElement" Click="Click_GoToElement" Tag="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Path=Row.Header}"/>
        </ContextMenu.Items>
    </ContextMenu>
</DataGrid.Resources>

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow" BasedOn="{StaticResource {x:Type DataGridRow}}">
        <Setter Property="ContextMenu" Value="{StaticResource RowContextMenu}" />
    </Style>
</DataGrid.RowStyle>

Then , click-event looks like this. I am receiving an error: object reference not set to an instance of an object

private void Click_GoToElement(object sender, RoutedEventArgs e)
{
    try
    {
        var row = ((System.Windows.Controls.MenuItem)sender).Tag;
        MessageBox.Show(row.ToString());
    }
    catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.StackTrace); }
}

Solution

  • Bind to the PlacementTarget of the parent ContextMenu:

    <MenuItem Header="GoToElement"
              Click="Click_GoToElement"
              Tag="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.Header}"/>