为什么应用此样式时我的功能区菜单按钮弹出窗口消失了?

Why does my Ribbon Menu Button Popup disappear when I apply this Style?

这是我的XAML:

<Ribbon x:Name="ribbonMain" Height="200" ContextMenu="{x:Null}" VerticalAlignment="Top" ShowQuickAccessToolBarOnTop="False" >

    <RibbonTab x:Name="ribbonTabMain" Header="Test Tab" ContextMenu="{x:Null}" >

        <RibbonGroup x:Name="ribbonGroupMain" Header="Test Group" ContextMenu="{x:Null}">
            <RibbonButton x:Name="ribbonButtonMain" Label="Test Button" ContextMenu="{x:Null}" />
        </RibbonGroup>

        <RibbonGroup x:Name="ribbonGroupMain2" Header="Test Group 2" ContextMenu="{x:Null}">
            <RibbonMenuButton ContextMenu="{x:Null}" Name="ribbonMenuButtonMain" Label="Menu Button">
                <RibbonMenuItem ContextMenu="{x:Null}" Name="ribbonMenuItemMain" Header="Menu Item"></RibbonMenuItem>
                <RibbonMenuItem ContextMenu="{x:Null}" Name="ribbonMenuItemMain2" Header="Menu Item 2"></RibbonMenuItem>
            </RibbonMenuButton>
        </RibbonGroup>

    </RibbonTab>

</Ribbon>

然后我运行此C#代码获取功能区菜单按钮默认控件模板:

string ribbonMenuButtonControlTemplate = XamlWriter.Save(ribbonMenuButtonMain.Template);

之后,我将控件模板的 x:Namex:Key 属性设置为某些内容,然后将 XAML 的字符串放入:

<Style TargetType="RibbonMenuButton" 
    <Setter Property="Template">
        <Setter.Value>
            {DefaultControlTemplateHere}
        </Setter.Value>
    </Setter>
</Style>

最后我把 Style 放在我的 <Window.Resources> 中。

我想从那里更改 Style,但后来我意识到弹出窗口不再工作了。 我预计不会有任何改变。看来我错了。 为什么会这样?

注:

我已经尝试 运行使用此代码来查看弹出窗口是否会打开:

if (!ribbonMenuButtonMain.IsDropDownOpen)
{
    ribbonMenuButtonMain.IsDropDownOpen = true;
}

没有 Style 应用该代码 运行 没问题,弹出窗口打开。 但是对于 Style 我得到了这个例外:

System.InvalidOperationException: 'This Visual is not connected to a PresentationSource.'

XamlWriter.Save 方法有一些提到的序列化限制 here。其中之一就是;

Common references to objects made by various markup extension formats, such as StaticResource or Binding, will be dereferenced by the serialization process. These were already dereferenced at the time that in-memory objects were created by the application runtime, and the Save logic does not revisit the original XAML to restore such references to the serialized output.

因此您生成的模板缺少一个 TemplateBindingPopupIsOpen 属性:

<Popup ... IsOpen="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsDropDownOpen}">

您可以使用反编译器从 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\System.Windows.Controls.Ribbon.dll 提取默认模板,包括任何绑定,例如 dotPeek