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

相关推荐
The Shio1 小时前
OptiByte 操练场:面向 IoT/嵌入式的协议可视化调试工具
网络·嵌入式硬件·物联网·c#·.net·业界资讯·iot
龙侠九重天3 小时前
C# 调用 TensorFlow:迁移学习与模型推理实战指南
人工智能·深度学习·机器学习·c#·tensorflow·迁移学习·tensorflow.net
我是唐青枫4 小时前
C#.NET YARP 认证授权实战:在网关层统一接入 JWT
开发语言·c#·.net
暖馒4 小时前
WPF绑定由简到繁深入笔记
笔记·wpf
程序leo源4 小时前
Linux深度理解
linux·运维·服务器·c语言·c++·青少年编程·c#
白菜上路5 小时前
C# .net 生成版本号自动变更
c#·.net·visual studio
加号35 小时前
【C#】 通过 Python.NET 调用 Python pyd 扩展模块:多类交互与参数传递实践指南
python·c#·.net
petunsecn5 小时前
MongoDB C# Driver 在 `ElemMatch + Contains + 类型转换` 下的翻译差异
mongodb·c#
东方.既白5 小时前
WPF炫酷界面DEMO
wpf
她说彩礼65万5 小时前
C# WIFI连接状态检测方法
java·spring·c#