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

相关推荐
用户4488466710602 小时前
.NET进阶——深入理解Lambda表达式(2)手搓LINQ语句
c#·.net
狮恒4 小时前
OpenHarmony Flutter 分布式设备发现与连接:无感组网与设备协同管理方案
分布式·flutter·wpf·openharmony
云和数据.ChenGuang4 小时前
鸿蒙负一屏的技术定位与核心价值
华为·wpf·harmonyos
狮恒5 小时前
OpenHarmony Flutter 分布式数据管理实战:全场景数据一致性与高效流转方案
wpf
狮恒5 小时前
OpenHarmony Flutter 分布式音视频:跨设备流传输与实时协同交互方案
分布式·flutter·wpf·openharmony
狮恒6 小时前
OpenHarmony Flutter 分布式安全与隐私保护:跨设备可信交互与数据防泄漏方案
分布式·flutter·wpf·openharmony
狮恒6 小时前
OpenHarmony Flutter 分布式智能协同:基于 AI 的跨端场景感知与自适应交互方案
wpf
狮恒8 小时前
OpenHarmony Flutter 分布式任务调度:跨设备资源协同与负载均衡方案
分布式·flutter·wpf·openharmony
云中飞鸿8 小时前
wpf 类图
c#
嗝o゚9 小时前
Flutter适配鸿蒙多屏异构UI开发实战
flutter·开源·wpf·harmonyos