tags:

views:

369

answers:

2

While defining style in resource dictionary you can use either

x:Name="xyz"

and

x:Type="xyz". 

and can reference this style in XAML like {StaticResource xyz}.

Most examples use 'x:Key', and the difference between 'name' and 'key' is that using 'x:name' lets you use this style definition code-behind?

FIXES: The question is totally wrong. What was intended to be asked was the difference between x:Key and x:Name. But didn't go trying this code myself, but was just relying on memories - thought I have both in ResourceDictionary, which was wrong. And I also didn't have such code in

 <xxx.Resources > 

sections, since it doesn't work either. You can't reference Style that doesn't have x:Key (x:Name doesn't work here), and adding two styles without x:Key throws exception since both get the same (empty?) key in dictionary.

Ray puts all the difference in a very nice way, thanks.
My fault

+1  A: 

x:Name allows you to create a reference that you can use by name.

x:type allows you to create a reference that is used by that type

for instance

<Style TargetType="{x:Type Button}">
    ...
</Style>

creates a style that will automatically affect buttons

Mike B
+3  A: 

This is a trick question. In fact, you cannot define a style in a ResourceDictionary using either

x:Type="xyz"

or

x:Name="xyz"

Here is the difference:

  • x:Type="xyz" is not valid XAML syntax.
  • x:Name="xyz" is actually valid XAML syntax that names an object (which affects the generation of code-behind) but does not provide a dictionary key.
  • x:Key="xyz" is also valid XAML syntax that provides a dictionary key but does not name an object.

In a dictionary a key is required, so you must specify x:Key (except that for FrameworkTemplate and its subclasses the key can be inferred from the TargetType or DataType). In a dictionary you may also specify x:Name if desired but it does not affect the key.

Note that x:Type is a markup extension that is predefined by XAML, whereas x:Name and x:Key are actual XAML keywords. So x:Type can only be used in markup extension syntax as the value of a property:

something="{x:Type whatever}"

whereas x:Name and x:Key are attributes that can be used on elements.

Ray Burns
It's a double trick question because actually **neither of them works**. You can't define a style in a ResourceDictionary using `x:Name="xyz"` either. Only x:Key works.
itowlson
No kidding! How did I miss that? And now what am I going to do? Delete my answer? Amend it? I guess I'll amend it. Thanks itowlson.
Ray Burns
Thanks for response. Please, let me know if I should delete this question, or edit its text to make it not tricky.
bybor