x:Name與Name有兩個不同點:
1、x:Name是Xaml的標記特性,任何在Xaml中定義的元素,都可以使用x:Name來爲元素指定名稱。
Name是FrameworkElement定義的依賴項屬性(String類型),只有FrameworkElement的派生類纔可以使用Name。
例如,Ellipse的Fill屬性的類型是Brush,Brush不是FrameworkElement的子類,它沒有Name屬性。
因此,在Xaml中,爲Brush指定名稱時,只能使用x:Name標記特性:
- <!--Xaml code-->
- <Ellipse>
- <Ellipse.Fill>
- <SolidColorBrush x:Name="aliceBlue" Color="AliceBlue"/>
- <!--註銷上面一行的代碼,使用下面一行的代碼無法通過編譯-->
- <!--<SolidColorBrush Name="aliceBlue" Color="AliceBlue"/>-->
- </Ellipse.Fill>
- </Ellipse>
2、在FrameworkElement的定義中,添加了System.Windows.Markup.RuntimeNamePropertyAttribute特性:
該特性的作用是,當在Xaml中,使用x:Name後,該值將被自動賦給FrameworkElement的Name屬性。
可以使用RuntimeNamePropertyAttribut,爲自己定義的類添加名稱特性:
[RuntimeNamePropertyAttribute("N1")]
[RuntimeNamePropertyAttribute("N2")]
public class Person : UIElement
{
public String N1 { get; set; }
public String N2 { get; set; }
}
- <StackPanel>
- <wp:Person x:Name="WebAttack"/>
- <TextBlock>Name:</TextBlock>
- <TextBlock Text="{Binding ElementName=WebAttack, Path=N1}"/>
- <TextBlock>Nickname:</TextBlock>
- <TextBlock Text="{Binding ElementName=WebAttack, Path=N2}"/>
- </StackPanel>