
实现代码
- <TextBlock Text="右键弹出菜单">
- <TextBlock.ContextMenu>
- <ContextMenu ItemsSource="{local:ClassTypeTreeDataProvider IsRecursion=True, Type={x:Type FrameworkElement}}">
- <ContextMenu.ItemContainerStyle>
- <Style TargetType="MenuItem">
- <Setter Property="Command" Value="{local:ShowDialogCommand}"/>
- <Setter Property="CommandParameter" Value="{Binding Model}"/>
- Style>
- ContextMenu.ItemContainerStyle>
- <ContextMenu.ItemTemplate>
- <HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
- <DockPanel>
- <CheckBox VerticalAlignment="Center" IsChecked="{Binding IsChecked, Mode=TwoWay}" />
- <TextBlock VerticalAlignment="Center" 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 IsRecursion=True, Type={x:Type FrameworkElement}}">
- <Menu.ItemContainerStyle>
- <Style TargetType="MenuItem">
- <Setter Property="Command" Value="{local:ShowDialogCommand}"/>
- <Setter Property="CommandParameter" Value="{Binding Model}"/>
- Style>
- Menu.ItemContainerStyle>
- <Menu.ItemTemplate>
- <HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
- <TextBlock VerticalAlignment="Center" 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
HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频