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
本文作者:简亦
本文链接:https://www.cnblogs.com/KevinBran/p/17932260.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步