0
votes

I'm having problem assigning an event handler a contextmenu menuitem which is bound as a ItemContainerStyle for a listbox. When right clicking and invoking the listbox item in the application, I get a contextmenu which shows the header name as well as another nested item called system.window.style.

My XAML code is as follows:

            <ListBox HorizontalAlignment="Left" Margin="6,90,0,0" Name="listbox1" Width="189" FontSize="14" Height="416" VerticalAlignment="Top">
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="ContextMenu">
                        <Setter.Value>
                            <ContextMenu>
                                <MenuItem Header="Delayed Kick" >
                                    <Style TargetType="MenuItem">
                                        <EventSetter Event="Click" Handler="DelayedKick_Click"/>
                                    </Style>
                                </MenuItem>
                            </ContextMenu>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>
1

1 Answers

1
votes

Everything nested within a MenuItem is interpreted as that item's content, which may be child MenuItems, which is why is being displayed as a menu item.

The following example will work as you expect. Put the MenuItem style in a Resources element wherever is suitable.

<Grid.Resources>
    <Style TargetType="MenuItem">
        <EventSetter Event="Click" Handler="DelayedKick_Click"/>
    </Style>
</Grid.Resources>

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="ContextMenu">
            <Setter.Value>
                <ContextMenu>
                    <MenuItem Header="Delayed Kick" />
                </ContextMenu>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>