附加屬性(Attached Properties)基礎

附加屬性是Extensible Application MarkupLanguage (XAML) 定義的一個概念。 附加屬性旨在用作可在任何對象上設置的一類全局屬性。  Windows Presentation Foundation (WPF) 中,附加屬性通常定義爲沒有常規屬性“包裝”的一種特殊形式的依賴項屬性。也就是說,附加屬性是說一個屬性本來不屬於某個對象,是根據某種特殊需求附加到該對象的。

舉個形象的例子,去做火車,你就有了座位號這個屬性;假如不做火車就沒有這個屬性。

1. 附加屬性與普通依賴屬性

  • 通過RegisterAttached方法註冊而不是Register方法。
  • 沒有普通的.NET屬性包裝器,而是通過GetSet屬性名來實現屬性包裝。
  • 沒有普通的.NET屬性。

2.附加屬性的用途

  • 附加屬性的一個用途是允許不同的子元素爲實際在父元素中定義的屬性指定唯一值。最常用的就是Grid.RowGrid.ColumnDockPanel.Dock
  • 爲對象附加一些屬性。譬如爲DockPanel設置FontSize屬性,DockPanel本身沒有FontSize屬性,通過以下方法設置(DockPanel設置了字體,但是GroupBoxHeader是不受影響的,影響了其中的子元素)
<GroupBox Header="附加屬性用法1" Grid.Column="0" Grid.Row="0" >
	<DockPanel TextElement.FontSize="20">
		<Button Content="button1" DockPanel.Dock="Bottom" />
		<Button Content="button2" DockPanel.Dock="Right"/>
		<Button Content="button3" />
	</DockPanel>
</GroupBox>
效果如下:


3.代碼中的附加屬性

WPF中的附加屬性沒有用於簡化 get/set訪問的典型 CLR“包裝”方法。這是因爲附加屬性不是必須屬於設置它的實例的 CLR命名空間的一部分。但是,XAML讀取器必須能夠在處理 XAML時設置這些值。若要成爲有效的附加屬性,附加屬性的所有者類型必須實現 Get屬性名 Set屬性名形式的專用訪問器方法。這些專用的訪問器方法也有助於在代碼中獲取或設置附加屬性。從代碼的角度而言,附加屬性類似於具有方法訪問器(而不是屬性訪問器)的支持字段,並且該支持字段可以存在於任何對象上,而不需要專門定義。

下面的示例演示如何在代碼中設置附加屬性:

private void AddControl()
{
	Label label = new Label();
	label.Content = "通過代碼添加";
	mainGird.Children.Add(label);
	Grid.SetColumn(label, 0);
	Grid.SetRow(label, 1);
}

4.自定義附加屬性

實例:自定義一個角度附加屬性,使得控件對象旋轉一定的角度。

代碼如下:

依賴屬性實現:

namespace WPF_Properties
{
	using System.Windows;
	using System.Windows.Media;

	public class MyAttachedProperties : DependencyObject
	{
		public static double GetAngle(DependencyObject obj)
		{
			return (double)obj.GetValue(AngleProperty);
		}

		public static void SetAngle(DependencyObject obj, double value)
		{
			obj.SetValue(AngleProperty, value);
		}

		public static readonly DependencyProperty AngleProperty =
			DependencyProperty.RegisterAttached("Angle", typeof(double), typeof(MyAttachedProperties), new PropertyMetadata(0.0, OnAngleChanged));

		private static void OnAngleChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
		{
			var element = obj as UIElement;
			if (element != null)
			{
				element.RenderTransformOrigin = new Point(0.5, 0.5);
				element.RenderTransform = new RotateTransform((double)e.NewValue);
			}
		}	   
	}
}

XAML使用:

<GroupBox Header="附加屬性用法1" Grid.Column="0" Grid.Row="0" >
	<DockPanel TextElement.FontSize="20">
		<Button Content="button1" DockPanel.Dock="Bottom" local:MyAttachedProperties.Angle="180" />
		<Button Content="button2" DockPanel.Dock="Right" local:MyAttachedProperties.Angle="10"/>
		<Button Content="button3" />
	</DockPanel>
</GroupBox>

效果:





作者:FoolRabbit
出處:http://blog.csdn.net/rabbitsoft_1987
歡迎任何形式的轉載,未經作者同意,請保留此段聲明!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章