问题
On the msdn site there is big article: XAML overview
And there is the part describing what is: x:Key, x:Class, x:Name
etc. but the problem is that all that said there about it is very abstractional with no examples.
I know that when I create an element in xaml and set: x:Name = "abc"
then in the cs file I have access to this object by abc.fieldORmethod()
but what about the rest. Could anybody provide explanation with examples for that statements below?
x:Key
: Sets a unique key for each resource in aResourceDictionary
(or similar dictionary concepts in other frameworks). x:Key will probably account for 90% of the x: usages you will see in a typical WPF application's markup.x:Class
: Specifies the CLR namespace and class name for the class that provides code-behind for a XAML page. You must have such a class to support code-behind per the WPF programming model, and therefore you almost always see x: mapped, even if there are no resources.x:Name
: Specifies a run-time object name for the instance that exists in run-time code after an object element is processed. In general, you will frequently use a WPF-defined equivalent property for x:Name. Such properties map specifically to a CLR backing property and are thus more convenient for application programming, where you frequently use run time code to find the named elements from initialized XAML. The most common such property isFrameworkElement.Name
. You might still use x:Name when the equivalent WPF framework-level Name property is not supported in a particular type. This occurs in certain animation scenarios.x:Static
: Enables a reference that returns a static value that is not otherwise a XAML-compatible property.x:Type
: Constructs a Type reference based on a type name. This is used to specify attributes that take Type, such asStyle.TargetType
, although frequently the property has native string-to-Type conversion in such a way that the x:Type markup extension usage is optional.
回答1:
x:Key is used in case you want to define some resource which can be reused in your xaml. It is equivalent to Key of normal dictionary.
<Window.Resources>
<Style x:Key="ButtonStyle"/>
</Window.Resources>
x:Static is used to donate some static data. Suppose you want to declare brush with some static color defined under SystemColors enum.
<SolidColorBrush Color="{x:Static SystemColors.ControlColor}" />
x:Type is equivalent to Type
class in C#. It denotes type of class.
<Style TargetType="{x:Type Button}"/>
x:Name is used to provide name to control so that it can be accessed from code behind using that name or can be binded within XAML using ElementName.
<TextBlock x:Name="txt1" Text="Test"/>
<TextBlock x:Name="txt2" Text="{Binding Text,ElementName=txt}"/>
来源:https://stackoverflow.com/questions/20846610/meaning-of-xkey-xname-xtype-xstatic-in-xaml