WPF - 具有自定义 DefaultStyleKey 的自定义窗口会丢失 FocusVisualStyle

本文关键字:自定义 FocusVisualStyle 窗口 DefaultStyleKey WPF | 更新日期: 2023-09-27 17:57:23

我已经创建了一个自定义窗口,覆盖了它的DefaultStyleKey,但我丢失了窗口中包含的所有控件的FocusVisualStyle。即使是自定义的 FocusVisualStyle 也无法正常工作。我在这里错过了什么?

以下是我在 CustomWindow 类的静态 ctor 中重写 DefaultStyleKey 的方法:

DefaultStyleKeyProperty.OverrideMetadata( typeof( CustomWindow ), new FrameworkPropertyMetadata( typeof( CustomWindow ) ) );

下面是 generic.xaml 中定义的默认样式:

<Style TargetType="{x:Type local:CustomWindow}">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type local:CustomWindow}">
            <Border Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
               <ContentPresenter />
            </Border>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

下一步是将窗口的基本类型更改为自定义窗口,并添加两个按钮。使用 Tab 键导航时,不显示焦点矩形。

任何帮助将不胜感激!

WPF - 具有自定义 DefaultStyleKey 的自定义窗口会丢失 FocusVisualStyle

您需要将

ContentPresenter放在如下所示的AdornerDecorator中:

<AdornerDecorator>
    <ContentPresenter/>
</AdornerDecorator>

它是渲染所有焦点矩形的装饰器装饰器。

当事情不起作用时,您可以查看默认控件模板。 然后你试试他们的模板和你的模板,找出为什么一个有效而另一个无效!

我抬头看了看Window,它看起来像这样:

<Style x:Key="{x:Type Window}"
       TargetType="{x:Type Window}">
    <Setter Property="Foreground"
            Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
    <Setter Property="Background"
            Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Window}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <AdornerDecorator>
                        <ContentPresenter/>
                    </AdornerDecorator>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="Window.ResizeMode"
                 Value="CanResizeWithGrip">
            <Setter Property="Template"
                    Value="{StaticResource WindowTemplateKey}"/>
        </Trigger>
    </Style.Triggers>
</Style>