2023-7-27WPF的ContextMenu的传参绑定方式
WPF的ContextMenu的绑定方式
【作者】长生
ContextMenu为何不能正常绑定
在wpf中ContextMenu和ToolTip一样都是弹出层,与VisualTree已经分离了,只不过ToolTip在wpf中有进行特殊处理,所以可以正常绑定。
个人觉得ContextMenu绑定的最可靠的方式
- 首先添加BindingProxy类,继承Freezable,Freezable权限很高,可以实现可靠的数据绑定。
- 添加依赖属性object,方便传值。
public class BindingProxy : Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new PropertyMetadata(null));
}
- 在xaml页面资源中添加命名空间,并添加控件绑定
xmlns:viewModel="clr-namespace:xxxxxxx"
<UserControl.Resources>
<viewModel:BindingProxy x:Key="runRecordList" Data="{Binding ElementName=runRecordList}" />//绑定到需要传值的控件
</UserControl.Resources>
- 在Context将改控件绑定到CommandParameter,即可对其进行传参。当然也可以直接绑定到ContextMenu上的DataContext,这样就可以直接对Command和ComandParameter进行绑定,再次我就不一一列举了。
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem
Command="{Binding OpenCommand}"CommandParameter="{Binding Source={StaticResource runRecordList}, Path=Data.SelectedItem}"Header="打开" />
</ContextMenu>
</DataGrid.ContextMenu>
- 当然也可以引用外部资源DiscreteObjectKeyFrame进行绑定,方法和上述类似
使用PlacementTarget
在WPF中,PlacementTarget是一个属性,用于指定弹出式控件(如ContextMenu、ToolTip等)的放置目标。它定义了弹出式控件相对于哪个元素进行定位和显示。
PlacementTarget属性通常用于设置弹出式控件的放置位置。例如,当使用ContextMenu时,可以将ContextMenu的PlacementTarget属性设置为一个控件,以便在该控件上右键单击时显示ContextMenu。这样,ContextMenu将相对于该控件进行定位并显示。
<ListBox.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Command="{Binding DeleteCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem.Id}" Header="删除" />
</ContextMenu>
</ListBox.ContextMenu>
结尾
感谢您的阅读,如果有收获麻烦点个关注!⭐
其他平台
公众号:【长生小殿】
B站:【月长生殿主】
分类:
【常用功能】C# WPF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2021-07-27 2021-7-27 泛型基本练习
2021-07-27 2021-7-27 反射的基本练习