Significance Of x:Key Attribute

Each object declared as a resource must set the x:Key property. This property will be used by other elements to access the resource. But for the Style objects, there is an exception. Style objects that set the TargetType property do not need to set the 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 the above example, the x:Key property has been used, so, the style will be visible on the Button only when the Style property is used explicitly on an 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 the above example, the style will be applied by default on all the buttons (due to the TargetType) as no x:Key has been defined in the Style resource. The code for the button is shown below:

<Button Name="btnShow" Width="60" Height="30" />
Ebook Download
View all
Learn
View all