I have a ContextMenu on a DataGrid and I'm trying to capture the MenuItem.Click event for all the menu items. Like so:

<DataGrid Name="dataGridMembers" Grid.Row="1" Grid.ColumnSpan="15"
          AutoGenerateColumns="False" SelectionMode="Single"
          ItemsSource="{Binding MemberList}" RowHeaderWidth="5"
          MouseDoubleClick="dataGridMembers_MouseDoubleClick"
          MenuItem.Click="NewReservationContextMenuClick">
    <DataGrid.ContextMenu>
        <ContextMenu Name="GridMenu">
            <MenuItem 
                Name="AddSponsoredSingle"
                Header="Add Sponsored Single" />
            <Separator />
            <MenuItem 
                Name="EditNote"
                Header="Add/Edit Note" />
            <Separator />
            <MenuItem 
                Name="AddMale"
                Header="Add Male" />
            <MenuItem 
                Name="AddFemale"
                Header="Add Female"/>
            <MenuItem 
                Name="AddCouple"
                Header="Add Couple"/>
        </ContextMenu>
    </DataGrid.ContextMenu>
    <DataGrid.Columns>
     ...
    </DataGrid.Columns>
</DataGrid>

The problem is the event never fires. MenuItem.Click is supposed to be a bubbled event and I should be able to catch it anywhere in the visual tree.

What am I doing wrong?

EDIT: adding the handler in code works fine. The following line in the constructor of the .xaml.cs and all is good.

GridMenu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(NewReservationContextMenuClick));
有帮助吗?

解决方案

The ContextMenu is opened in a Popup control, which is not part of the visual tree of its logical parent.

In order to have a common Click handler for all MenuItems, move the handler to the ContextMenu element:

<DataGrid Name="dataGridMembers" Grid.Row="1" Grid.ColumnSpan="15" 
          AutoGenerateColumns="False" SelectionMode="Single" 
          ItemsSource="{Binding MemberList}" RowHeaderWidth="5" 
          MouseDoubleClick="dataGridMembers_MouseDoubleClick" 
          > 
    <DataGrid.ContextMenu> 
        <ContextMenu Name="GridMenu"
             MenuItem.Click="NewReservationContextMenuClick"> 
            ...
        </ContextMenu>

其他提示

You could also use a style for all MenuItems to assign the event handler:

<DataGrid.Resources>
    <Style TargetType="{x:Type MenuItem}">
        <EventSetter Event="Click" Handler="NewReservationContextMenuClick" />
    </Style>
</DataGrid.Resources>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top