1.依赖属性的效果
一旦规定视觉树上一个对象的fontsize属性,那么属于他的节点之下的所有对象都会沿袭这个属性,然而如果某个子节点明确的设定了自己的fontsize,就不会沿袭父节点的fontsize属性。fontsize这个属性是在Contorl中定义的,它具有默认值,默认的值优先级最低,从父节点上沿袭来的fontsize优先级比默认高,而直接对对象本身进行设置的优先级最高。类似fontsize属性的这类属性就是依赖属性
2.依赖属性的实现
class="brush:csharp;collapse:true;;gutter:true;">using System; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace LY.SetSpaceProperty { public class SpaceButton : Button { //传统的字段和属性 string txt; public string Text { set { txt = value; Content = SpaceOutText(txt); } get { return txt; } } //依赖属性 public static readonly DependencyProperty SpaceProperty; public int Space { set { SetValue(SpaceProperty, value); } get { return (int)GetValue(SpaceProperty); } } //用静态构造函数初始化 static SpaceButton() { //定义元数据 FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata(); metadata.DefaultValue = 1; metadata.AffectsMeasure = true; metadata.Inherits = true; metadata.PropertyChangedCallback += OnSpacePropertyChanged; // 注册到依赖属性 SpaceProperty = DependencyProperty.Register("Space", typeof(int), typeof(SpaceButton), metadata, ValidateSpaceValue); } //回调方法用于值的验证 static bool ValidateSpaceValue(object obj) { int i = (int)obj; return i >= 0; } //回调方法用于属性改变 static void OnSpacePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { SpaceButton btn = obj as SpaceButton; btn.Content = btn.SpaceOutText(btn.txt); } string SpaceOutText(string str) { if (str == null) return null; StringBuilder build = new StringBuilder(); foreach (char ch in str) build.Append(ch + new string(' ', Space)); return build.ToString(); } } }
上面自定义了一个依赖属性,fontsize属性也是以类似上面的方式定义。
进一步深入参见:http://www.cnblogs.com/zhouyongh/archive/2009/09/10/1564099.html
http://www.cnblogs.com/BillGan/archive/2011/05/26/2057859.html
http://www.cnblogs.com/jimson/archive/2010/07/29/DependencyProperties.html
http://www.cnblogs.com/HelloMyWorld/archive/2013/02/21/2920149.html