Bastian
Bastian

Reputation: 23

C# WPF ContextMenu: MenuItem does not react to click

I have a C# WPF-Application. In the XAML i have a Datagrid, to which I have added a ContextMenu, that looks like this:

<DataGrid.ContextMenu>
  <ContextMenu ItemsSource="{Binding Categories}">
    <ContextMenu.ItemTemplate>
      <DataTemplate>
        <MenuItem Header="{Binding Name}" Background="{Binding Brush}" Click="MenuItem_Click" Tag="{Binding Id}" />
      </DataTemplate>
    </ContextMenu.ItemTemplate>
  </ContextMenu>
</DataGrid.ContextMenu>

When using the application it looks like this: https://i.sstatic.net/ohZP4.jpg

The problem is, that when clicking the color part of the box (which I'm guessing is part of some internal grid) the MenuItem_Click event is fired. However, when I'm clicking on the grey part of the MenuItem the click event is not fired. Does anyone know why it behaves this way? And is there a way to fix this?

Additionally, it would be great to be able to color the whole menu item, not just the small box inside. Is there a way to do this?

Upvotes: 2

Views: 1993

Answers (1)

mm8
mm8

Reputation: 169400

You could try to decrease the Padding of the ContextMenu and the BorderThickess of the MenuItems:

<DataGrid.ContextMenu>
    <ContextMenu ItemsSource="{Binding Categories}" Padding="0">
        <ContextMenu.ItemTemplate>
            <DataTemplate>
                <MenuItem Header="{Binding Name}" Background="{Binding Brush}" Click="MenuItem_Click" Tag="{Binding Id}"
                          BorderThickness="0"/>
            </DataTemplate>
        </ContextMenu.ItemTemplate>
    </ContextMenu>
</DataGrid.ContextMenu>

Or

<DataGrid.ContextMenu>
    <ContextMenu ItemsSource="{Binding Categories}" Padding="0">
        <ContextMenu.ItemContainerStyle>
            <Style TargetType="MenuItem">
                <Setter Property="Header" Value="{Binding Name}" />
                <Setter Property="Tag" Value="{Binding Id}" />
                <Setter Property="Background" Value="{Binding Brush}" />
                <EventSetter Event="Click" Handler="MenuItem_Click" />
            </Style>
        </ContextMenu.ItemContainerStyle>
    </ContextMenu>
</DataGrid.ContextMenu>

Upvotes: 1

Related Questions