x:Name與Name區別

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標記特性:

  1. <!--Xaml code-->  
  2.   
  3. <Ellipse>  
  4.    <Ellipse.Fill>  
  5.        <SolidColorBrush x:Name="aliceBlue" Color="AliceBlue"/>  
  6.        <!--註銷上面一行的代碼,使用下面一行的代碼無法通過編譯-->  
  7.        <!--<SolidColorBrush Name="aliceBlue" Color="AliceBlue"/>-->  
  8.    </Ellipse.Fill>  
  9. </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; } 
}

  1.     <StackPanel>  
  2.         <wp:Person x:Name="WebAttack"/>  
  3.         <TextBlock>Name:</TextBlock>  
  4.         <TextBlock Text="{Binding ElementName=WebAttack, Path=N1}"/>  
  5.         <TextBlock>Nickname:</TextBlock>  
  6.         <TextBlock Text="{Binding ElementName=WebAttack, Path=N2}"/>  
  7.     </StackPanel>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章