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

相关推荐
Aevget1 小时前
界面控件DevExpress WPF v25.1新版亮点:AI功能的全面升级
c#·.net·wpf·界面控件·devexpress·ui开发
Archy_Wang_12 小时前
Hangfire 入门与实战:在 .NET Core 中实现可靠后台任务处理
c#·.netcore
爱编程的鱼5 小时前
想学编程作为今后的工作技能,学哪种语言适用性更强?
开发语言·算法·c#·bug
清风与日月6 小时前
c#事件委托示例
开发语言·c#
用户3721574261356 小时前
C# 实现在 Excel 中高效生成和操作表格
c#
csdn_aspnet6 小时前
C# 金字塔体积计算程序(Program for volume of Pyramid)
c#
William_cl7 小时前
C# ASP.NET MVC Model 分类:数据传输对象(DTO)—— 跨层传数的 “精简快递“
c#·asp.net·mvc
zwjapple7 小时前
Kafka 从入门到精通完整指南
c#·linq
唐青枫9 小时前
C#.NET SemaphoreSlim 深入解析:轻量级异步锁与并发控制
c#·.net
我是苏苏12 小时前
C#高级:程序查询写法性能优化提升策略(附带Gzip算法示例)
开发语言·算法·c#