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

相关推荐
qq_5896660513 分钟前
C语言、C++与C#的区别详解
c语言·c++·c#
Vae_Mars1 小时前
WPF中的Lazy<T>使用方法
wpf
淡海水1 小时前
04-02-哈希-Dictionary-TKey-TValue-上-核心数据结构
数据结构·算法·c#·哈希算法·编译·字典·dictionary
longxiaozhang62 小时前
C#异常处理:程序出错了怎么办?
开发语言·数据库·c#
zQ.ii3 小时前
WPF 触发器学习笔记
笔记·学习·wpf
界面开发小八哥3 小时前
界面控件DevExpress WinForms中文帮助文档 - 入门指南
ai·c#·.net·devexpress·ui开发·winforms
清风与日月4 小时前
Yitter.IdGenerator:高性能分布式唯一ID生成器详解
分布式·c#·.net·.netcore
影寂ldy5 小时前
C# WinForm TCP-Socket
网络·tcp/ip·c#
czhc11400756635 小时前
2026-08-25 博客:现场排查的 8 个坑
c#
Z5998178416 小时前
c#软件开发学习笔记--WPF(控件、样式)
笔记·学习·c#