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

相关推荐
亘元有量-流量变现5 分钟前
鸿蒙、安卓、苹果音频设备技术深度解析与开发实践
android·wpf·harmonyos·亘元有量·积分墙
软泡芙9 分钟前
【Bug】ReactiveUI WPF绑定中依赖属性不更新的问题分析与解决方案
java·bug·wpf
浪扼飞舟13 分钟前
WPF输入验证(ValidationRule)
java·javascript·wpf
View1213813 小时前
在 .NET 中使用 Moonshot Kimi + AgentFramework:从 SDK 到 Agent 的完整实践
c#·agent·kimi
FlDmr4i2815 小时前
.NET 10 & C# 14 New Features 新增功能介绍-扩展成员Extension Members
开发语言·c#·.net
QJtDK1R5a16 小时前
C# 14 中的新增功能
开发语言·c#
雨浓YN18 小时前
WebApi 通讯-DeepSeek API调用文档
c#
yuan1999719 小时前
C# 断点续传下载文件工具设计与实现
开发语言·c#
雨浓YN21 小时前
WebApi 通讯-自写Demo技术文档
c#
唐青枫1 天前
C#.NET TPL Dataflow 深入解析:数据流管道、背压控制与实战取舍
c#·.net