What is the difference between t开发者_C百科he following TargetType specifications?
1.
<Style TargetType="{x:Type Button}" ...
2.
<Style TargetType="Button" ...
It seems the both works fine.
In the first example, the Type
markup extension creates an instance of Type
specified by the given string, i.e. Button
.
In the second example, the type converter associated with the TargetType
property converts the string "Button"
into the required Type
.
Both give exactly the same result. Notably, in Silverlight the Type
markup extension does not exist so (2) is only possible.
Sorry for poking such an old thread but I feel it's worth it. I have recently encountered a situation which shows that x:Type
is different from TypeName-as-String
. From my experience -
x:Type considers the strong name or the version of the assembly but not TypeName-as-String.
I have explained about my scenario and other details in my blog here -
http://weblogs.asp.net/akjoshi/archive/2012/02/03/importance-of-specifying-ancestortype-with-x-type-in-relativesourcebinding.aspx
Apart from this, there is also difference in how WPF infers the type. For x:Type TypeExtension is used, whereas for TypeName-as-String FrameworkElementFactory is used.
As per MSDN -
Type Properties That Support Typename-as-String
WPF supports techniques that enable specifying the value of some properties of type Type without requiring an x:Type markup extension usage. Instead, you can specify the value as a string that names the type. Examples of this are ControlTemplate.TargetType and Style.TargetType. Support for this behavior is not provided through either type converters or markup extensions. Instead, this is a deferral behavior implemented through FrameworkElementFactory.
http://msdn.microsoft.com/en-us/library/ms753322.aspx
精彩评论