隐式样式不适用于自定义控件

时间:2013-08-23 21:25:14

标签: wpf xaml resources implicit-style

在我的App.xaml中,我有一些隐式样式

<Style TargetType="{x:Type Button}">
   ...Blah...
</Style>

这些样式适用于控件,只要它们不在我创建的自定义控件中。

我的控制

 public class NavigationControl : Control
 {
     public static readonly DependencyProperty ButtonStyleProperty =
         DependencyProperty.Register("ButtonStyle", typeof(Style), typeof(NavigationControl));

     public Style ButtonStyle
     {
         get { return (Style)GetValue(ButtonStyleProperty); }
         set { SetValue(ButtonStyleProperty, value); }
     }
 }

 static NavigationControl()
 {
     DefaultStyleKeyProperty.OverrideMetadata(typeof(NavigationControl), new FrameworkPropertyMetadata(typeof(NavigationControl)));
 }

 public NavigationControl()
 {
 }

我的控件样式和模板

<ControlTemplate x:Key="NavigationControlTemplate" TargetType="{x:Type controls:NavigationControl}">
   <Button Style="{TemplateBinding ButtonStyle}"
</ControlTemplate>

<Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="MinWidth" Value="75"/>
    <Setter Property="Height" Value="50"/>
    <Setter Property="FontSize" Value="12"/>
    <Setter Property="Margin" Value="-1"/>
</Style>

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource DefaultButtonStyle}">
    <Setter Property="Template" Value="{StaticResource NavigationButtonTemplate}"/>
</Style>

<Style TargetType="{x:Type controls:NavigationControl}">
     <Setter Property="Template" Value="{StaticResource NavigationControlTemplate}"/>
     <Setter Property="ButtonStyle" Value="{StaticResource ButtonStyle}"/>
</Style>

现在我假设DefaultButtonStyle的BasedOn将从App级别获取它。但它没有。应用应用程序级别样式的唯一方法是通过创建NavigationControl类型的样式来覆盖ButtonStyle。

隐式样式是否有办法使其有效?

1 个答案:

答案 0 :(得分:2)

设置BasedOn="{StaticResource {x:Type Button}}"将获得WPF的默认按钮样式。如果您想使用App.xaml中定义的样式,则需要为该样式添加一个键,以便您可以从控件样式中引用它:

<强>的App.xaml

<!-- Your style, just with an added x:Key -->
<Style x:Key="myButtonStyle" TargetType="{x:Type Button}">
   ...
</Style>

<!-- Set the above style as a default style for all buttons -->
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource myButtonStyle}">

您的控件样式和模板

<Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource myButtonStyle}">
    ...
</Style>