1. 什么是附加属性(attached property )
附加属性依赖属性的一种特殊形式,常见的Grid.Row,Canvas.Left都是附加属性。
/// <summary>// 从指定元素获取 Left 依赖项属性的值。/// </summary>/// <param name="obj">The element from which the property value is read.</param>/// <returns>Left 依赖项属性的值</returns>public static double GetLeft(DependencyObject obj){
return (double)obj.GetValue(LeftProperty);}/// <summary>/// 将 Left 依赖项属性的值设置为指定元素。/// </summary>/// <param name="obj">The element on which to set the property value.</param>/// <param name="value">The property value to set.</param>public static void SetLeft(DependencyObject obj, double value){
obj.SetValue(LeftProperty, value);}/// <summary>/// 标识 Left 依赖项属性。/// </summary>public static readonly DependencyProperty LeftProperty =
DependencyProperty.RegisterAttached("Left", typeof(double), typeof(MyCanvas), new PropertyMetadata(0d));附加属性的简单定义如上述代码所示。可以看出和依赖属性不同的地方在于没有作为属性包装器的Setter和Getter,而多了两个静态函数GetXXX和SetXXX。并且注册标识符使用DependencyProperty.RegisterAttached而不是DependencyProperty.Register。
2. 附加属性有什么作用
和依赖属性不同的地方在于,依赖属性是依赖对象本身的属性,附加属性是附加在其他对象身上的属性,通俗来说就是在别的对象内插入自己的属性。上面提到的Grid.Row,就是Grid将Row属性附加到没有Row属性的其它类中,以便进行布局。
