What is the difference between x:Key and x:Name in WPF?
x:Key is only valid inside a resource dictionary and is added to a dictionary, x:Name is used locally and represents a variable within the class.
x:Name is used to name UI elements (e.g. Controls, Panels etc), whereas x:Key is used to identify resources (which can be more or less anything) within a ResourceDictionary.
This means that you can't reference things in a resource dictionary using an x:Name value:
<Grid>
<Grid.Resources>
<Style x:Name="StyleName" x:Key="StyleKey" />
</Grid.Resources>
<Button Style="{StaticResource StyleName}" /> <!-- Will not work-->
<Button Style="{StaticResource StyleKey}" /> <!-- Will work -->
</Grid>
You will also notice that elements that are not within a resource dictionary cannot have an x:Key attribute:
<TextBox x:Key="TextBoxKey" /> <!-- Will not compile -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With