5. 完整的自定义依赖属性
5.1 定义
/// <summary>/// 标识 Title 依赖属性。/// </summary>public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyPage), new PropertyMetadata(string.Empty));/// <summary>/// 获取或设置Content的值/// </summary> public object Content{ get { return (object)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); }}/// <summary>/// 标识 Content 依赖属性。/// </summary>public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(object), typeof(MyPage), new PropertyMetadata(null, OnContentChanged));private static void OnContentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args){ MyPage target = obj as MyPage; object oldValue = (object)args.OldValue; object newValue = (object)args.NewValue; if (oldValue != newValue) target.OnContentChanged(oldValue, newValue);}protected virtual void OnContentChanged(object oldValue, object newValue){}
以上代码为一个相对完成的依赖属性例子(还有一些功能比较少用就不写出了),从这段代码可以看出,自定义依赖属性的步骤如下: