做网站的控件,邯郸微信公众号开发,东莞网络营销推广公司,游戏设计培训机构有哪些一、目的#xff1a;开发过程中#xff0c;有些模块的右键ContextMenu菜单是需要动态显示的#xff0c;既是根据不同条件显示不同的菜单#xff0c;很多是通过代码去生成ContextMenu的MenuItem#xff0c;本文介绍通过绑定的方式去加载ContextMenu#xff0c;Menu菜单栏的…一、目的开发过程中有些模块的右键ContextMenu菜单是需要动态显示的既是根据不同条件显示不同的菜单很多是通过代码去生成ContextMenu的MenuItem本文介绍通过绑定的方式去加载ContextMenuMenu菜单栏的同样适用原理同TreeView的绑定 二、效果 三、环境 VS2022
四、实现
实现代码 TextBlock Text右键弹出菜单TextBlock.ContextMenuContextMenu ItemsSource{local:ClassTypeTreeDataProvider IsRecursionTrue, Type{x:Type FrameworkElement}}ContextMenu.ItemContainerStyleStyle TargetTypeMenuItemSetter PropertyCommand Value{local:ShowDialogCommand}/Setter PropertyCommandParameter Value{Binding Model}//Style/ContextMenu.ItemContainerStyleContextMenu.ItemTemplateHierarchicalDataTemplate ItemsSource{Binding Nodes}DockPanelCheckBox VerticalAlignmentCenter IsChecked{Binding IsChecked, ModeTwoWay} /TextBlock VerticalAlignmentCenter Text{Binding Model.Name} //DockPanel/HierarchicalDataTemplate/ContextMenu.ItemTemplate/ContextMenu/TextBlock.ContextMenu/TextBlock 原理跟TreeView一样应用ItemsSource绑定数据源应用HierarchicalDataTemplate模板作为ItemTemplate来绑定树结构的绑定参考文档
示例:WPF中TreeView自定义TreeNode泛型绑定对象-CSDN博客
示例:WPF中TreeView自定义TreeNode泛型绑定对象来实现级联勾选-CSDN博客
Menu的绑定原理一样 实现代码 Menu ItemsSource{local:ClassTypeTreeDataProvider IsRecursionTrue, Type{x:Type FrameworkElement}}Menu.ItemContainerStyleStyle TargetTypeMenuItemSetter PropertyCommand Value{local:ShowDialogCommand}/Setter PropertyCommandParameter Value{Binding Model}//Style/Menu.ItemContainerStyleMenu.ItemTemplateHierarchicalDataTemplate ItemsSource{Binding Nodes}TextBlock VerticalAlignmentCenter Text{Binding Model.Name} //HierarchicalDataTemplate/Menu.ItemTemplate/Menu
当切换ItemsSource既可以实现动态切换ContextMenu
五、需要了解的知识点
ContextMenu 类 (System.Windows.Controls) | Microsoft Learn
Menu 类 (System.Windows.Controls) | Microsoft Learn
HierarchicalDataTemplate 类 (System.Windows) | Microsoft Learn
MenuItem 类 (System.Windows.Controls) | Microsoft Learn
ICommand 接口 (System.Windows.Input) | Microsoft Learn
六、源码地址
GitHub - HeBianGu/WPF-ControlDemo: 示例
GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库
GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库
七、了解更多
System.Windows.Controls 命名空间 | Microsoft Learn
https://github.com/HeBianGu
HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频