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

相关推荐
❀always❀1 小时前
深入浅出分布式限流(更新中)
分布式·wpf
每日出拳老爷子3 小时前
[C#] 使用TextBox换行失败的原因与解决方案:换用RichTextBox的实战经验
开发语言·c#
程序猿多布11 小时前
C# 值拷贝、引用拷贝、浅拷贝、深拷贝
c#
阿蒙Amon13 小时前
C#随机数生成全面详解:从基础到高级应用
服务器·网络·c#
开开心心_Every13 小时前
便捷的电脑自动关机辅助工具
开发语言·人工智能·pdf·c#·电脑·音视频·sublime text
深漂阿碉15 小时前
WPF打包exe应用的图标问题
wpf
三千道应用题15 小时前
WPF学习笔记(26)CommunityToolkit.Mvvm与MaterialDesignThemes
wpf
我要打打代码15 小时前
C#Winform窗体显示模糊的问题
c#
阿蒙Amon15 小时前
C#正则表达式全面详解:从基础到高级应用
开发语言·正则表达式·c#
水果里面有苹果17 小时前
19-C#静态方法与静态类
java·开发语言·c#