views:

72

answers:

3

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

+5  A: 

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.

Leom Burke
+2  A: 

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 -->
Steve Greatrex
+1  A: 

Yes, you would use x:Key to assign a key to resources inside a ResourceDictionary, either locally in the resources section for an element or a specific ResourceDictionay. This key is then used to look up the resource, through {DynamicResource XXX} or {StaticResource XXX}.

x:Name is used to assign a name to a control in xaml. This can then be used to access the element in the code behind file, using the usual syntax or using an ElementName binding inside the file.

Max Palmer