Skip to main content

WPF: Significance of x:Key attribute


Each object declared as resource must set x:Key property. This property will be used by another elements to access the resource. But for Style objects, there is an exception. Style objects that set the TargetType property do not need to set x:Key explicitly because it is set implicitly behind the scenes.

Scenario1: When x:Key is defined
<Style x:Key="myStyle" TargetType="Button">
      <Setter Property="Background" Value="Yellow"/>
</Style>
In above example, x:Key property is used, so, style will be visible on Button, only when Style property is used explicitly on element, as shown in below snippet:
<Button Style="{StaticResource myStyle}" Width="60" Height="30" />

Scenario2:When x:Key is not defined
<Style TargetType="Button">
    <Setter Property="Background" Value="Yellow"/>
</Style>
In above example, style will be applied by default on all the buttons (due to TargetType) as no x:Key is defined in Style resource. Code for the button is shown below:
<Button Name="btnShow" Width="60" Height="30" />

Comments