WPF 学习笔记5 附加属性
1, 附加对象的意思是一个属性本来不属于某一个对象,但是由于某种需求而被后来加上。
Like: <TextBox Text=”text” Grid.Column=”1” Grid.Row=”1”/>
2,下面是一个例子,我们创建一个School类,然后给他添加一个GradeProperty的附加属性:(使用Propa+2Tab)
public class School : DependencyObject { public static int GetGrade(DependencyObject obj) { return (int)obj.GetValue(GradeProperty); } public static void SetGrade(DependencyObject obj, int value) { obj.SetValue(GradeProperty, value); } // Using a DependencyProperty as the backing store for Grade. This enables animation, styling, binding, etc... public static readonly DependencyProperty GradeProperty = DependencyProperty.RegisterAttached("Grade", typeof(int), typeof(School), new PropertyMetadata(0)); }看最后这句话,使用的DependencyProperty.RegisterAttached方法。
看看如何使用:
*先创建一个Human类
public class Human : DependencyObject
{
}* 使用:
Human human =new Human();
School.SetGrade(human,6);
int grade = School.GetGrade(human);
3. 原理:
其实和DependecnyPropery一样,这个附加属性的值也是存放在Human实例的EffectiveValueEntry数组中,只是由于在数组中检索值所用到的依赖属性 不是以Human类为宿主,而是以School类为宿主。 这样当然也不会冲突,因为他们有唯一个GlobalIndex
4. 其他的需要注意的地方:
**<Button Content=”OK” Grid.Column=”1” Grid.Row=”1”/>
可以写成:
Grid.SetColumn(button,1);
Grid.SetRow(buttton,1);
** 附加属性其实也是依赖属性,也是可以Binding的。看个例子:
<Rectangle x:Name=”rect” Fill=”Blue” Width=”30” Height=”30’
Canvas.Left=”{Binding ElementName=sliderX,Path=Value}” />
等价于:
this.rect.SetBinding(Canvas.LeftProperty,new Binding(“Value”){Source=SliderX});