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

相关推荐
一丝晨光15 分钟前
逻辑运算符
java·c++·python·kotlin·c#·c·逻辑运算符
friklogff29 分钟前
【C#生态园】从图像到视觉:Emgu.CV、AForge.NET、OpenCvSharp 全面解析
开发语言·c#·.net
△曉風殘月〆2 小时前
WPF颜色(SolidColorBrush)和Win32颜色(COLOREF)互转的方法
wpf·win32·solidcolorbrush·colorref
friklogff3 小时前
【C#生态园】构建你的C#操作系统:框架选择与实践
服务器·开发语言·c#
code bean5 小时前
【C#基础】函数传参大总结
服务器·开发语言·c#
shanshan20996 小时前
上位机系统架构 | 如何设计一个高效的多相机管理系统
c#·wpf·相机
ling1s8 小时前
C#基础(13)结构体
前端·c#
.Net Core 爱好者8 小时前
Redis实践之缓存:设置缓存过期策略
java·redis·缓存·c#·.net
云草桑8 小时前
逆向工程 反编译 C# net core
前端·c#·反编译·逆向工程
充值内卷10 小时前
WPF入门教学四 WPF控件概述
windows·ui·wpf