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

相关推荐
逝水无殇17 小时前
C# 异常处理详解
开发语言·后端·c#
玖玥拾19 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
逝水无殇20 小时前
C# 文件的输入与输出详解
开发语言·数据库·后端·c#
唐青枫1 天前
看懂 IL 的关键:C#.NET 栈机执行模型实战拆解
c#·.net
我才是银古1 天前
从零构建 Windows 桌面 RPA 框架:Go 与 .NET 的跨语言协奏
c#·go·rpa
逝水无殇1 天前
C# 正则表达式详解
开发语言·后端·正则表达式·c#
朱永博1 天前
使用Onnruntime实现Padim/Patchcore推理
开发语言·c#
吴可可1231 天前
C# CAD二次开发添加带按钮的窗口
c#
铅笔侠_小龙虾1 天前
Rust 学习(8)-切片类型
学习·rust·c#
习明然2 天前
我的本地化AI项目(三)
人工智能·python·electron·c#·avalonia