WPF styles: difference between x:Name and x:Type

痞子三分冷 提交于 2020-01-23 06:31:48

问题


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:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2162425/wpf-styles-difference-between-xname-and-xtype

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!