WPF 嵌套ListBox选中项右键不响应
时间: 2023-09-03 10:16:50 浏览: 78
这个问题可能是因为 ListBox 的 ItemTemplate 中包含了另一个 ListBox,而右键事件被内部的 ListBox 捕获而不是外部的 ListBox。解决这个问题的方法是在内部 ListBox 的 ItemContainerStyle 中添加一个 PreviewMouseRightButtonDown 事件处理程序,并将事件标记为已处理,以防止它被继续传递到外部 ListBox。
示例代码如下:
```xml
<ListBox ItemsSource="{Binding OuterItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding InnerItems}"
ItemContainerStyle="{StaticResource InnerListBoxItemStyle}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- Inner ListBox ItemContainerStyle -->
<Style x:Key="InnerListBoxItemStyle" TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseRightButtonDown" Handler="InnerListBoxItem_PreviewMouseRightButtonDown" />
</Style>
```
```csharp
private void InnerListBoxItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
```
这里,我们在 InnerListBoxItemStyle 中添加了 PreviewMouseRightButtonDown 事件处理程序,并将事件标记为已处理。这样,右键事件就不会被内部的 ListBox 捕获,而会传递到外部的 ListBox 中。