#138 – Dependency Property Value Sources: #4 – Implicit Style

The fourth source in the list of sources for the base value of a dependency property is an implicit style.  This rule applies only to the Style dependency property.

The Style property obtains its value implicitly when a style is applied to all elements whose type matches the specified TargetType of the style.

Since an explicit style is treated as a local value, the resulting precedence list for the Style property, highest to lowest, is:

  • Explicit style (local value)
  • Implicit style
  • Default value

In the example below, we use an implicit style to set the style of two different Button elements.

    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Control.FontStyle" Value="Italic"/>
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button Content="Click Me" Height="23" Width="125" />
        <Button Content="Or Me" Height="23" Width="125" />
    </StackPanel>

Advertisements

#137 – The Value of the Style Property Comes From One of Three Places

The Style property is the one dependency property that doesn’t follow the full list of property value precedence rules.  Its value can come from one of three different sources, listed below.

  1. Explicit style – Style is explicitly specified, either inline in XAML, as a resource, or specified in code.  Treated as a local value
  2. Implicit style – Style is applied to all elements whose type matches the target type of the style
  3. Default – No style is specified, default styling used

Here’s an example of an explicit style.

    <Window.Resources>
        <Style x:Key="anItalicButton">
            <Setter Property="Control.FontStyle" Value="Italic"/>
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button Content="Click Me" Height="23" Width="125" Style="{StaticResource anItalicButton}"/>
        <Button Content="Or Me" Height="23" Width="125" />
    </StackPanel>

Here’s an example of an implicit style, applied to all Button elements.

    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Control.FontStyle" Value="Italic"/>
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button Content="Click Me" Height="23" Width="125" />
        <Button Content="Or Me" Height="23" Width="125" />
    </StackPanel>