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

相关推荐
云草桑2 小时前
.net AI MCP 入门 适用于模型上下文协议的 C# SDK 简介(MCP)
ai·c#·.net·mcp
工程师0074 小时前
C#中堆和栈的概念
c#·堆和栈
weixin_307779134 小时前
C#实现MySQL→Clickhouse建表语句转换工具
开发语言·数据库·算法·c#·自动化
CsharpDev-奶豆哥11 小时前
ASP.NET中for和foreach使用指南
windows·microsoft·c#·asp.net·.net
The Sheep 202314 小时前
WPF自定义路由事件
大数据·hadoop·wpf
阳光雨滴14 小时前
使用wpf用户控件编程落石效果动画
c++·wpf
cimeo15 小时前
【C 学习】12.2-函数补充
学习·c#
wuty00715 小时前
WPF 调用 ChangeWindowMessageFilterEx 修改指定窗口 (UIPI) 消息筛选器的用户界面特权隔离
wpf·sendmessage·changewindowmessagefilterex·uip·消息筛选器的用户界面特权隔离·window message
晚枫~18 小时前
零基础快速上手Playwright自动化测试
javascript·python·测试工具·c#·自动化
爱编程的鱼18 小时前
C# 变量详解:从基础概念到高级应用
java·算法·c#