C#:列表框项目的列表框上下文菜单 (WPF)

标签 c# wpf listbox contextmenu listboxitem

我想在 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/

相关文章:

c# - 升级 .NET Framework 后 VS2010 出现 "Unable to step. Process is not synchronized"错误

c# - 如何使我的 InfiniteLoopingList 类实现 IEnumerable?

vb.net - 检查 listbox1 中是否已存在某个项目

java - ZK Java BandBox Image 点击 autoDrop + new ListItem into ListBox

wpf - WPF ListBox SelectedItem问题

c# - 如何缓存 HttpResponseMessage 返回的图像

c# - 在表达式树中组合表达式

c# - WPF 将 RowDefinition.Height 属性绑定(bind)到 DataTemplate 中 Height=Auto 的另一个 RowDefinition

c# - 我有一个由 6 个不同标签共享的上下文菜单,我如何知道哪个标签正在使用上下文菜单的当前实例?

.net - ImageBrush 可以多线程工作吗?