I defined a context menu in the resources of a Datarid. In the Click event of the context menu I want to check the name of the parent control (DataGrid). I tried VisualTreeHelper.GetParent() and LogicalTreeHelper.GetParent() but neither reflects the hierarchy in the xaml. How do I get the DataGrid Control from the Click event? Thanks for your answers.
Code:
private void datagridTargetDelete_Click(object sender, RoutedEventArgs e)
{
// Check the name of the DataGrid here...
}
XAML:
<DataGrid Name="datagridTarget">
<DataGrid.Resources>
<ContextMenu x:Key="DGTContextMenu">
<MenuItem Header="Delete" Click="datagridTargetDelete_Click">
<MenuItem.Icon>
<Image Height="16" Width="16" Source="{Binding ContextDeleteIcon}"/>
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header="" Width="Auto" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image ContextMenu="{DynamicResource DGTContextMenu}" Height="16" Width="16" Source="{Binding ObjectImage}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
You might want to consider a RoutedCommand with a CommandBinding on the parent element in this case. This is actually how ContextMenu is supposed to be used, I think. That way, WPF would find the parent object for you, you wouldn’t have to search the logical tree for it.