我想在 WPF 中为我的列表框提供一个上下文菜单。 我是用整个列表框的上下文菜单来实现的,但是即使您没有单击某个项目,也可以通过单击来获取上下文菜单。
我在谷歌上找到了一些东西,但这没有成功。
我试过这样的:
<ListBox Margin="5" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="{Binding Name}" Click="MenuItemName_Click"/>
<MenuItem Header="{Binding Capital}" Click="MenuItemCapital_Click"/>
<MenuItem Header="{Binding Population}" Click="MenuItemPopulation_Click"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我尝试使用示例中的文本 block ,以及其他教程中的其他元素,我厌倦了它没有和许多其他东西 - 但没有任何效果。我的列表框项目没有上下文菜单:(
后来我尝试了这样的事情:
<ListBox.ItemTemplate>
<DataTemplate>
<ListBoxItem>
<ListBoxItem.ContextMenu>
<ContextMenu>
<MenuItem/>
</ContextMenu>
</ListBoxItem.ContextMenu>
</ListBoxItem>
</DataTemplate>
</ListBox.ItemTemplate>
但是还是不行。
有人可以给我一个提示/工作示例:)吗?
谢谢
最佳答案
我会在 ListBoxItem
的样式中设置 ContextMenu
,而不是在 DataTemplate
中:
<ListBox Name="simpleListBox"
ItemsSource="{Binding SimpleList}"
DisplayMemberPath="Name">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
...
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
关于C#:列表框项目的列表框上下文菜单 (WPF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4418631/