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

相关推荐
三千道应用题1 小时前
WPF学习笔记(12)下拉框控件ComboBox与数据模板
wpf
Accpdaiyekun2 小时前
C# 操作mongodb 多次查询快还是使用管道查询速度快
mongodb·c#·lua
界面开发小八哥2 小时前
界面组件DevExpress WPF中文教程:Grid - 如何获取节点?
.net·wpf·界面控件·devexpress·ui开发
Dm_dotnet2 小时前
C#:wpf ui 4.0 是如何实现页面导航的?
c#
三千道应用题2 小时前
WPF学习笔记(22)项面板模板ltemsPanelTemplate与三种模板总结
wpf
圆滚滚肉肉4 小时前
后端MVC(控制器与动作方法的关系)
后端·c#·asp.net·mvc
ajassi20004 小时前
开源 C# .net mvc 开发(六)发送邮件、定时以及CMD编程
linux·开源·c#·mvc
我是唐青枫4 小时前
C#.NET NLog 详解
开发语言·c#·.net
向宇it5 小时前
【unity游戏开发——网络】网络游戏通信方案——强联网游戏(Socket长连接)、 弱联网游戏(HTTP短连接)
网络·http·游戏·unity·c#·编辑器·游戏引擎
一线码农6 小时前
MinHook 如何对 .NET 母体 CoreCLR 进行拦截
c#·.net·代码注入