问题描述
我有一个上下文菜单 - 问题是,我需要它仅仅是点击一个ListViewItem的时候打开。现在,如果我在ListView或在头的任意位置单击它会打开。
I have a context menu - problem is I need it to only open when a listviewitem is clicked. Right now it will open if I click anywhere in the listview or in the header.
<ListView>
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="More Info" Command="{Binding MoreInfo}" />
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView>
<!-- columns and stuff here -->
</GridView>
</ListView.View>
</ListView>
我曾尝试添加的ContextMenu作为一种资源,并把它当成一种风格,但是这打破了命令(点击详细信息应该打开一个对话窗口,不起作用这种方式)
I have tried adding the ContextMenu as a resource and applying it as a style, but this breaks the command (clicking on More Info should open a dialog window, doesnt work this way)
<ListView.Resources>
<ContextMenu x:Key="ItemContextMenu">
<MenuItem Header="More Info" Command="{Binding MoreInfo}" Background="WhiteSmoke" />
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}" >
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}" />
</Style>
</ListView.ItemContainerStyle>
所以不知道如何限制上下文菜单只有ListViewItem的,并具有指挥工作。
So not sure how to restrict the context menu to only the listviewitem and have the command work.
推荐答案
使用的模板结合,这将工作:
Use the RelativeSource in the command binding in the template, and it will work:
<ListView.Resources>
<ContextMenu x:Key="ItemContextMenu">
<MenuItem Header="More Info" Command="{Binding Path=DataContext.MoreInfo, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" Background="WhiteSmoke" />
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}" >
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}" />
</Style>
</ListView.ItemContainerStyle>
这篇关于文本菜单的ListViewItem的唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!