silverlight提供了属性系统,管理依赖属性。依赖属性的用途在于提供一种方法基于其他输入的值计算属性。这些其他输入可以包括外部属性、实时属性确定机制、重用模板或者通过对象树中其他元素的父子关系获得的值,还以可以提供将更改传播到其他属性的回调。【示例源码下载】
下面就来给Button添加一个依赖属性:
- public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
- "Text", typeof(string), typeof(ButtonExpand), null);
- public string Text
- {
- get { return (string)GetValue(TextProperty); }
- set { SetValue(TextProperty, value); }
- }
通过这种方式就给类ButtonExpand扩展了一个依赖属性。
也可以通过propertyChangedCallbac在属性改变时创建一个回调函数。实现代码如下:
- public event DependencyPropertyChangedEventHandler TextPropertyChanged;
- public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
- "Text", typeof(string), typeof(ButtonExpand), new PropertyMetadata(new PropertyChangedCallback(ButtonExpand.OnTextPropertyChanged)));
- public string Text
- {
- get { return (string)GetValue(TextProperty); }
- set { SetValue(TextProperty, value); }
- }
- private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- (d as ButtonExpand).OnTextPropertyChanged(e);
- }
- void OnTextPropertyChanged(DependencyPropertyChangedEventArgs e)
- {
- if (TextPropertyChanged != null)
- { TextPropertyChanged(null,e); }
- }
silverlight给控件添加依赖属性时,不定义DefaultStyleKey样式就继承父类的样式,如果定义了可以使用用户自定义样式,一条语句就可以搞定:
- public ButtonExpand()
- {
- this.DefaultStyleKey = typeof(ButtonExpand);
- }
有时候我们需要在模板生效的时候对某些模板成员进行操作,如绑定事件、调整属性等,就需要通过overrride父类OnApplyTemplate来响应模板生效。,下面代码演示了在模板生效时改变背景颜色。
- public override void OnApplyTemplate()
- {
- base.OnApplyTemplate();
- (GetTemplateChild("Background") as Border).Background = new SolidColorBrush(Colors.Red);
- }