WPF当单击ContextMenu时获取ListView项的名称 [英] WPF Get name of ListView item when ContextMenu clicked

查看:260
本文介绍了WPF当单击ContextMenu时获取ListView项的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表视图,其中装有项目.每个项目都有一个关联的ContextMenu.当用户右键单击ListView中的这些项目之一并单击ContextMenu中的按钮之一时,我需要获取被单击的ListView中的项目名称.

I have a list view that's populated with items. Each of these items has a ContextMenu attached to it. When a user right clicks on one of these items in the ListView and clicks one of the buttons in the ContextMenu I need to get the name of the item in the ListView that was clicked.

我的ListView的XAML如下所示:

My XAML for the ListView looks like this:

<ListView.Resources>
    <ContextMenu x:Key="ItemContextMenu">
        <MenuItem Click="Download" Header="Download" 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>

当我右键单击并单击名为下载"的MenuItem时,将调用Download()函数.

When I right click and click the MenuItem called "Download", the Download() function is called.

这是Download()的代码:

Here's the code for Download():

private void Download(object sender, RoutedEventArgs e)
{
    ListViewItem selectedItem = list.SelectedItem as ListViewItem;
    Console.WriteLine("Download clicked!");
    if (selectedItem == null)
    {
        Console.WriteLine("It's nothing!");
    }
}

从ListView中选择的项始终为null.是因为当用户右键单击带来在上下文菜单中,不再从技术上选择ListViewItem?我该如何解决?

The selected item from the ListView is always null. Is it because when the user right clicks to bring up the context menu the ListViewItem is no longer technically selected? How do I fix this?

推荐答案

您可以利用 PlacementTarget 获取ContextMenu的父级.

You can utilize the PlacementTarget to get the ContextMenu's parent.

PlacementTarget 是一个DependencyProperty,它使您可以引用包含被调用的ContextMenu的可视树.

The PlacementTarget is a DependencyProperty that allows you to reference the Visual Tree that holds the invoked ContextMenu.

当将ContextMenu分配给FrameworkElement.ContextMenu或FrameworkContentElement.ContextMenu属性时, ContextMenuService在ContextMenu打开时将此属性的此值更改为拥有的FrameworkElement或FrameworkContentElement.,设置ContextMenuService.PlacementTarget属性.

When the ContextMenu is assigned to the FrameworkElement.ContextMenu or FrameworkContentElement.ContextMenu property, the ContextMenuService changes this value of this property to the owning FrameworkElement or FrameworkContentElement when the ContextMenu opens. To use a different UIElement, set the ContextMenuService.PlacementTarget property.

请参阅: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆