gpt4 book ai didi

WPF 从 ListViewItem 上的 ContextMenu 获取引用的项目

转载 作者:行者123 更新时间:2023-12-04 19:47:11 24 4
gpt4 key购买 nike

我在每个具有 Click 事件的 ListViewItem 上都有一个带有 ContextMenuListView,如何在事件处理程序中检测在此 ContextMenu 中单击了哪个项目?我需要项目ID

 <Style TargetType="{x:Type ListViewItem}">

。..

 <Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="tv:TreeListViewItem">
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Open in current tab" Click="MenuItemCurrentTab_Click"/>
<MenuItem Header="Open in new tab" Click="MenuItemNewTab_Click"/>
</ContextMenu>
</Grid.ContextMenu>

最佳答案

this线程..

按照与链接中的答案相同的方式

<Grid.ContextMenu> 
<ContextMenu>
<MenuItem Header="Open in current tab"
Click="MenuItemCurrentTab_Click"
CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Parent}"/>

...

private void MenuItemCurrentTab_Click(object sender, RoutedEventArgs e)
{
MenuItem menuItem = sender as MenuItem;
if (menuItem != null)
{
ContextMenu parentContextMenu = menuItem.CommandParameter as ContextMenu;
if (parentContextMenu != null)
{
ListViewItem listViewItem = parentContextMenu.PlacementTarget as ListViewItem;
}
}
}

更新

添加此项以从 Grid 中获取父 ListViewItem

public T GetVisualParent<T>(object childObject) where T : Visual
{
DependencyObject child = childObject as DependencyObject;
while ((child != null) && !(child is T))
{
child = VisualTreeHelper.GetParent(child);
}
return child as T;
}

private void MenuItemCurrentTab_Click(object sender, RoutedEventArgs e)
{
MenuItem menuItem = sender as MenuItem;
if (menuItem != null)
{
ContextMenu parentContextMenu = menuItem.CommandParameter as ContextMenu;
if (parentContextMenu != null)
{
Grid grid = parentContextMenu.PlacementTarget as Grid;
ListViewItem listViewItem = GetVisualParent<ListViewItem>(grid);
}
}
}

关于WPF 从 ListViewItem 上的 ContextMenu 获取引用的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4015882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com