Difference between x:Key and x:Name

 Posted by Ddd on 2/24/2011 | Category: WPF Interview questions | Views: 7779 | Points: 40

x:Key and x:Name

These are both the XAML attributes that are specified in the declaration of XAML elements.


It is used mainly with the WPF Stylesheets or in ResourceDictionaries.

x is the namespace prefix
Key is the element specified by the x namespace prefix

x:Key is not applicable for user interface elements like the Button

<Window x:Class="WpfApplication1.Window1"
Title="Window1" Height="300" Width="300">

<Style x:Key="One" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="Green"/>
<!--how key is applied-->
<Button Height="100" Width="100" Style="{StaticResource One}" Content="good"/>


using the Key element, we can refer the StyleSheet defined in <Style></Style> tag in some other

<Style></Style> tag or in the declaration of some user interface element.

In the above example, I have mentioned how Key is used to define the Style of a Button.


It is used to mention the names of StyleSheets as well as the user interface controls
<Button Height="100" Width="100" x:Name="mybutton" Content="good"/>

x:Name can also be accessed in the code-behind (.xaml.cs /.xaml.vb), but x:Key cannot be accessed in code behind

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response