gpt4 book ai didi

c# - 重用上下文菜单

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:05 25 4
gpt4 key购买 nike

我已经创建了一个上下文菜单,我(目前)将其用于 TreeView 中的某些项目。为此,我创建了一个 TreeItem包含所有相关信息的类,如标题、图标、子项、执行目标等。这就是它的样子:

<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}"
Visibility="{Binding ShowContextMenu}"
ItemsSource="{Binding ContextMenu}">
<ContextMenu.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Header}" />
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command"
Value="{Binding Execute}" />
<Setter Property="Icon"
Value="{StaticResource cmIcon}" />
<Setter Property="ToolTip"
Value="{Binding ToolTip}" />
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>
</HierarchicalDataTemplate>
</ContextMenu.ItemTemplate>
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command"
Value="{Binding Execute}" />
<Setter Property="Icon"
Value="{StaticResource cmIcon}" />
<Setter Property="ToolTip"
Value="{Binding ToolTip}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>

当我仅在 TreeView 中使用上下文菜单时,它附加到 ItemTemplate 中的 TextBlock。但现在我想对不同的控件使用相同的上下文菜单。因为我不想将相同的代码复制到不同的位置并多次维护它,所以我想将它作为模板重用。我尝试了两件事:

  • 我将上下文菜单放在用户控件的资源中(仅用于测试)并这样调用它:<TextBlock Text="{Binding Header}" ContextMenu="{StaticResource myContextMenu}"> .会显示,但不会关闭也不会移动。此外,这也没什么用,因为我想在不同的用户控件上使用上下文菜单。

  • 然后我将上下文菜单放在 App.xaml 中的控件模板中:<ControlTemplate x:Key="TreeContextMenu" TargetType="ContextMenu"> .我这样调用它:

    <TextBlock.ContextMenu>
    <ContextMenu Template="{StaticResource TreeContextMenu}"/>
    </TextBlock.ContextMenu>

程序启动,但是当我想打开上下文菜单时,出现异常:'ContextMenu' cannot have a logical or visual parent.

我曾尝试通过谷歌搜索解决方案,但找不到任何有用的信息。

最佳答案

您正在尝试在上下文菜单中创建上下文菜单。从 App.xaml 中删除 ControlTemplate 标记,并将 x:Key 属性直接移动到 ContextMenu 标记。

此外,删除 TextBlock.ContextMenu 并将 ContextMenu="{StaticResource TreeContextMenu}" 属性添加到 TextBlock 标记。

关于c# - 重用上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16631951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com