Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between x:Key and x:Name

What is the difference between x:Key and x:Name in WPF?

like image 700
Jeaf Gilbert Avatar asked Jul 09 '10 08:07

Jeaf Gilbert


2 Answers

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.

like image 68
Leom Burke Avatar answered Sep 20 '22 01:09

Leom Burke


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 -->
like image 26
Steve Greatrex Avatar answered Sep 23 '22 01:09

Steve Greatrex