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

相关推荐
leo__5209 小时前
C#与三菱PLC串口通信源码实现(基于MC协议)
开发语言·c#
墨瑾轩10 小时前
C# PictureBox:5个技巧,从“普通控件“到“图像大师“的蜕变!
开发语言·c#·swift
墨瑾轩10 小时前
WinForm PictureBox控件:3个让图片“活“起来的骚操作,90%的开发者都踩过坑!
开发语言·c#
Jackson@ML15 小时前
2026最新版Visual Studio安装使用指南
ide·c#·visual studio
莫生灬灬17 小时前
VueMultiBrowser 5.0 开源 - 基于 Vue3 + CEF 的多浏览器管理器
chrome·开源·c#·自动化·多开·cef3
xb113218 小时前
C#异步编程入门概念及核心概念
开发语言·c#
gc_229920 小时前
学习C#调用OpenXml操作word文档的基本用法(19:学习文档页脚类)
c#·word·openxml·页脚·footerpart
baivfhpwxf202321 小时前
C# Task.Run 和 Task.Factory.StartNew 的区别
开发语言·c#
数据的世界011 天前
C# 封装、继承、多态 通俗解释
c#
人工智能AI技术1 天前
【C#程序员入门AI】AI应用的操作系统:Semantic Kernel 2026实战
人工智能·c#