热门:网页模板.net视频教程JQueryMVCjsonExtJs源码示例三级联动JQuery菜单
您现在的位置:.Net中文社区>> Silverlight>>正文内容

Silverlight DependencyObject 依赖属性

发布时间:2010年11月25日点击数: 佚名

silverlight提供了属性系统,管理依赖属性。依赖属性的用途在于提供一种方法基于其他输入的值计算属性。这些其他输入可以包括外部属性、实时属性确定机制、重用模板或者通过对象树中其他元素的父子关系获得的值,还以可以提供将更改传播到其他属性的回调。【示例源码下载

下面就来给Button添加一个依赖属性:

  1. public static readonly DependencyProperty TextProperty = DependencyProperty.Register( 
  2.            "Text"typeof(string), typeof(ButtonExpand), null); 
  3.  
  4.        public string Text 
  5.        { 
  6.            get { return (string)GetValue(TextProperty); } 
  7.            set { SetValue(TextProperty, value); } 
  8.        } 

通过这种方式就给类ButtonExpand扩展了一个依赖属性。
也可以通过propertyChangedCallbac在属性改变时创建一个回调函数。实现代码如下:

  1.  public event DependencyPropertyChangedEventHandler TextPropertyChanged; 
  1. public static readonly DependencyProperty TextProperty = DependencyProperty.Register( 
  2.             "Text"typeof(string), typeof(ButtonExpand), new PropertyMetadata(new PropertyChangedCallback(ButtonExpand.OnTextPropertyChanged))); 
  3.  
  4.         public string Text 
  5.         { 
  6.             get { return (string)GetValue(TextProperty); } 
  7.             set { SetValue(TextProperty, value); } 
  8.         } 
  9.  
  10.         private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
  11.         { 
  12.             (d as ButtonExpand).OnTextPropertyChanged(e); 
  13.         } 
  14.  
  15.         void OnTextPropertyChanged(DependencyPropertyChangedEventArgs e) 
  16.         { 
  17.             if (TextPropertyChanged != null
  18.             { TextPropertyChanged(null,e); } 
  19.         } 

silverlight给控件添加依赖属性时,不定义DefaultStyleKey样式就继承父类的样式,如果定义了可以使用用户自定义样式,一条语句就可以搞定:

  1. public ButtonExpand() 
  2.        { 
  3.            this.DefaultStyleKey = typeof(ButtonExpand); 
  4.        } 

有时候我们需要在模板生效的时候对某些模板成员进行操作,如绑定事件、调整属性等,就需要通过overrride父类OnApplyTemplate来响应模板生效。,下面代码演示了在模板生效时改变背景颜色。

  1. public override void OnApplyTemplate() 
  2.        { 
  3.            base.OnApplyTemplate(); 
  4.  
  5.            (GetTemplateChild("Background"as Border).Background = new SolidColorBrush(Colors.Red); 
  6.        } 

本站热点业务

更多模板/案例展示

关于我们 | 联系我们 | 团队日志 | 网站地图 | 网站合作