Answer:
x:Key and x:Name
These are both the XAML attributes that are specified in the declaration of XAML elements.
x:Key:
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
example:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style x:Key="One" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="Green"/>
</Style>
</Window.Resources>
<!--how key is applied-->
<Button Height="100" Width="100" Style="{StaticResource One}" Content="good"/>
</Window>
USES:
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.
x:Name:
It is used to mention the names of StyleSheets as well as the user interface controls
example:
<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