我正在尝试在ListBoxItem的上下文菜单上处理click事件。 XAML代码是:
<ListBox x:Name="LB_TranslationResult" HorizontalAlignment="Left" Height="128" Margin="254,71,0,0" VerticalAlignment="Top" Width="191">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Delete" Click="DeleteItem" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
DeleteItem事件如下所示:
private void DeleteItem(object sender, RoutedEventArgs e)
{
MessageBox.Show("Test");
}
很奇怪,但这个事件不起作用。出现上下文菜单,但是当我点击它的项目时没有任何反应。
请告诉我,这段代码有什么问题?
答案 0 :(得分:4)
将 Click 事件的事件处理程序包装到样式中,并使用EventSetter调用事件处理程序后面的代码:
<ListBox x:Name="LB_TranslationResult" HorizontalAlignment="Left" Height="128" Margin="254,71,0,0" VerticalAlignment="Top" Width="191">
<ListBox.Resources>
<Style x:Key="DeleteItemContextMenuStyle" TargetType="MenuItem">
<EventSetter Event="Click" Handler="DeleteItem"/>
</Style>
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Delete" Style="{StaticResource DeleteItemContextMenuStyle}"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>