开发者

don't run PropertyChangedCallback in DependencyProperty

开发者 https://www.devze.com 2023-04-09 01:00 出处:网络
I created a UserControl with a DependencyProperty. I set a value for this UserControl on FormLoad. But when I run the application no value is shown.

I created a UserControl with a DependencyProperty. I set a value for this UserControl on FormLoad. But when I run the application no value is shown.

My code:

  public static readonly DependencyProperty ValueProperty =
      DependencyPr开发者_如何转开发operty.Register("Value", typeof(PersianDateTime), typeof(UCDatePicker),
      new PropertyMetadata(PersianDateTime.Now, new PropertyChangedCallback((onchangedcallback))));

  public PersianDateTime Value
  {
      get { return (PersianDateTime)GetValue(ValueProperty); }
      set { SetValue(ValueProperty, value); }
  }


  private static void onchangedcallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  {
      UCDatePicker control = obj as UCDatePicker;
      PersianDateTime newdate = (PersianDateTime)e.NewValue;
      control.Years = ((PersianDateTime)e.NewValue).Year;
      control.Months = ((PersianDateTime)e.NewValue).Month;
      control.Days = ((PersianDateTime)e.NewValue).Day;
      control.Hours = ((PersianDateTime)e.NewValue).Hour;
      control.Minutes = ((PersianDateTime)e.NewValue).Minute;

  }

In my FormLoad:

uCDatePicker1.Value = PersianDateTime.Now;

when i use breakpoint ,onchangedcallback doesn't execute.


Because you don't change value,

Value is equal to PersianDateTime.Now before and after your assignment

onchangedcallback will be called only if you will assign different value to dependency property, you can change default value of dependency property to some default value if you want property changed event to be called at first assignment

If PersianDateTime is reference type(class for example) change your dependency property like this

 ...new PropertyMetadata(null,...

But looking on PersianDateTime type, seems it is struct so you can use

 ...new PropertyMetadata(DateTime.MinValue.ToPersianDateTime(),...

and it will work

Hope this helps

0

精彩评论

暂无评论...
验证码 换一张
取 消