wpf 仅用于 ListViewItem 的 ContextMenu

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18921188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:41:28  来源:igfitidea点击:

ContextMenu for ListViewItem only

c#wpfcontextmenulistviewitem

提问by ctd25

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.

我有一个上下文菜单 - 问题是我需要它只在单击 listviewitem 时打开。现在,如果我单击列表视图或标题中的任意位置,它将打开。

<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>

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)

我曾尝试将 ContextMenu 添加为资源并将其作为样式应用,但这会破坏命令(单击“更多信息”应打开一个对话框窗口,这种方式不起作用)

<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>

So not sure how to restrict the context menu to only the listviewitem and have the command work.

所以不确定如何将上下文菜单限制为仅 listviewitem 并让命令工作。

回答by Vyacheslav Volkov

Use the RelativeSourcein the command binding in the template, and it will work:

在模板中的命令绑定中使用RelativeSource,它将起作用:

<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>