WPF - 具有自定义DefaultStyleKey的自定义窗口失去了FocusVisualStyle

时间:2011-05-24 04:20:45

标签: c# wpf styles

我创建了一个自定义窗口覆盖它的 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>

下一步是将 MainWindow 的基本类型更改为 CustomWindow 并添加两个按钮。使用 Tab 键进行导航时,不会显示焦点矩形。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:4)

您需要将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>