首页 > 解决方案 > 包含具有绑定内容依赖属性的 contentpresenter 的自定义上下文菜单不在第二个窗口中显示内容

问题描述

我有一个自定义上下文菜单 ExtensibleContextMenu

<Style TargetType="controls:ExtensibleContextMenu" BasedOn="{StaticResource {x:Type ContextMenu}}" x:Shared="False">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:ExtensibleContextMenu}">
                    <DockPanel >
                          <ContentPresenter/>
                    </DockPanel>
             </ControlTemplate
        </Setter.Value>
    </Setter>
</Style>

带有附加的依赖属性 ContentProperty

public class ExtensibleContextMenu : ContextMenu
{
    public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content",
            typeof( object ),
            typeof( ExtensibleContextMenu ) );

    public object Content
    {
        get
        {
            return GetValue( ContentProperty );
        }

        set
        {
            SetValue( ContentProperty, value );
        }
    }}

content 属性设置为不同的样式。

   <Style TargetType="{x:Type controls:ExtensibleContextMenu}" BasedOn="{StaticResource {x:Type controls:ExtensibleContextMenu}}">
    <Setter Property="MinWidth" Value="400"/>
    <Setter Property="MaxWidth" Value="400"/>

    <Setter Property="Content">
        <Setter.Value>
          <ComboBox/>
        </Setter.Value>
    </Setter>

</Style>

样式化的 ExtensibleContentControl 用于可以打开两次的视图中。它默认在主窗口中打开。有什么工作正常。

此外,可以在另一个窗口中打开此视图。

当我打开另一个窗口时,主视图中的 extensibleContentControl 会丢失其内容,并且内容演示者不会在主窗口中显示任何内容。此外,主窗口中内容呈现器下的可视化树是空的。

任何人都知道这个问题可能来自哪里?谢谢!

标签: c#wpf

解决方案


将实际内容元素定义为资源x:Shared

<ComboBox x:Key="theContent" x:Shared="false">
    <ComboBoxItem>item...</ComboBoxItem>
</ComboBox>

...并将其设置为Style使用标记扩展:

<Style TargetType="{x:Type controls:ExtensibleContextMenu}" BasedOn="{StaticResource {x:Type controls:ExtensibleContextMenu}}">
    <Setter Property="MinWidth" Value="400"/>
    <Setter Property="MaxWidth" Value="400"/>
    <Setter Property="Content" Value="{StaticResource theContent}" />
</Style>

单个元素只能在可视化树中出现一次。


推荐阅读