WPF中 ContextMenu 寻找父物体的一种方案

据了解 ContextMenu 在WPF中实际是以类似于WIndow的呈现方式,所以 ContextMenu 在当前页面的 Visualtree 中是找不到的。

当在Listbox中需要传递当前选中项给ContextMenu时,需要以特殊手法传递。

前台XAML代码
复制代码
 <Grid>
     <Grid.RowDefinitions>
         <RowDefinition />
         <RowDefinition Height="auto" />
     </Grid.RowDefinitions>
     <Grid.ContextMenu>
         <ContextMenu>
             <MenuItem Command="{Binding Data.DeleteFileCommand, Source={StaticResource proxy}}" Header="Delete" />
             <MenuItem Command="{Binding RenameFileCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.PlacementTarget}" Header="Rename" />
             <!--  {Binding ElementName=listbox} cannot find  -->
             <MenuItem Command="{Binding OpenFilePathCommand}" Header="Open File Path" />
         </ContextMenu>
     </Grid.ContextMenu>
</Grid>

在这里通过指定ElementName的方式并不生效,因为这两个不在同一Visualtree下,虽然写的时候不报错,但是运行后就会报错。(在新版MAUI上写的时候就会报错)

RelativeSource的用法如下:RelativeSource

MenuItem 通过 RelativeSource 绑定到自身的父物体中的PlacementTarget属性(注意此时并没有代码提示可以自动完成),然后在后台就可以通过Command的参数接受前台父物体,此处演示为Grid对象;

后台C#代码

复制代码
 [RelayCommand]
 private void RenameFile(object obj)
 {
     var parent = obj as Grid;
     var txb = parent.FindName("txb1") as TextBox;
     if (txb != null)
     {
         IsEditFileName = true;
         txb.LostFocus += Txb_LostFocus;
         var res = txb.Focus();
     }
 }

完整示例可参考
https://github.com/KleinPan/One

相关推荐
IT策士2 小时前
Python Word操作:从入门到精通
python·c#·word
时光追逐者2 小时前
2026 年 .NET 客户端常用 MVVM 框架推荐
c#·.net·mvvm·.net core
xiaoshuaishuai84 小时前
C# 继承与虚方法
开发语言·windows·c#
月昤昽4 小时前
C#实现AutoCAD旋转与直径标注
c#·.net·二次开发·autocad·autocad二次开发
FL16238631294 小时前
基于C#winform实现yolo26-plate中文车牌检测识别支持12种中文双层颜色车牌文字识别
开发语言·c#
Eiceblue5 小时前
锁定单元格 :C# 控制 Excel 单元格编辑权限
开发语言·c#·excel
我是唐青枫5 小时前
C#.NET YARP 详解:用 ASP.NET Core 打造高性能反向代理网关
c#·.net
火星papa14 小时前
C# 阻塞队列(BlockingCollection)
c#·queue·阻塞队列
OctShop大型商城源码19 小时前
.NET线上商城源码_C#商城源码_技术赋能下的电商新生态
开发语言·c#·.net·商城系统源码
hixiong1231 天前
C#文件目录结构生成工具
开发语言·c#