依赖属性在自定义控件上的用法

 public static readonly DependencyProperty IsUpdateUIProperty =
          DependencyProperty.Register(
              "IsUpdateUI",
              typeof(bool),
              typeof(LoginStackPanel),
               new PropertyMetadata(false, (a, b) =>
               {
                   LoginStackPanel lsp = a as LoginStackPanel;
                   bool tempBool = (bool)b.NewValue;
                   if (b.Property == IsUpdateUIProperty && tempBool)
                   {
                       lsp.UpdateLoginUI();
                   }
               }));

        public bool IsUpdateUI
        {
            get { return (bool)GetValue(IsUpdateUIProperty); }
            set { SetValue(IsUpdateUIProperty, value); }
        }

注册最后一个参数是一个元数据,构造参数第一个个是默认值,后面一个参数是个委托,a表示当前类,b表示如下,

public sealed class DependencyPropertyChangedEventArgs
    {
        public object NewValue { get; }

        public object OldValue { get; }

        public DependencyProperty Property { get; }

 }

通常的用法是当新值和旧值达到某种要求是触发某种事件。

依赖属性不仅可以定义值类型和引用类型,还可以定义事件(其实还是一个类型)

public static readonly DependencyProperty UserLoginCompletedProperty =
          DependencyProperty.Register(
              "UserLoginCompleted",
              typeof(EventHandler),
              typeof(LoginStackPanel),
              null);

        public EventHandler UserLoginCompleted
        {
            get { return (EventHandler)GetValue(UserLoginCompletedProperty); }
            set { SetValue(UserLoginCompletedProperty, value); }
        }

 

 

posted @ 2013-12-04 11:00  haiziguo  阅读(409)  评论(0编辑  收藏  举报