How to create a bindable property in WPF?

13,894

Your dependency property implementation is missing a PropertyChangedCallback that gets called when the value of the property has changed. The callback is registered as a static method, which gets the current instance (on which the property has been changed) passed as its first parameter (of type DependencyObject). You have to cast that to your class type in order to access instance fields or methods, like show below.

public static readonly DependencyProperty DateProperty =
    DependencyProperty.Register("Date", typeof(DateTime), typeof(DaiesContainer),
    new PropertyMetadata(DateTime.Now, DatePropertyChanged));

public DateTime Date
{
    get { return (DateTime)GetValue(DateProperty); }
    set { SetValue(DateProperty, value); }
}

private void DatePropertyChanged(DateTime date)
{
    //...
}

private static void DatePropertyChanged(
    DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ((DaiesContainer)d).DatePropertyChanged((DateTime)e.NewValue);
}

Please note also that setting a default value of the dependency property is only done once for all instances of your class. Setting a value of DateTime.Now will hence produce the same default value for all of them, namely the time at which the static DependencyProperty is registered. I guess using something more meaningful, perhaps DateTime.MinValue, would be a better choice. As MinValue is already the default value of a newly created DateTime instance, you may even omit the default value from your property metadata:

public static readonly DependencyProperty DateProperty =
    DependencyProperty.Register("Date", typeof(DateTime), typeof(DaiesContainer),
    new PropertyMetadata(DatePropertyChanged));
Share:
13,894
Ali Jalali
Author by

Ali Jalali

Updated on June 12, 2022

Comments

  • Ali Jalali
    Ali Jalali almost 2 years

    i have a user control. I want to create a bindable property in my user control. I create a DependencyProperty as follows:

    public static readonly DependencyProperty DateProperty =
        DependencyProperty.Register("Date", typeof(DateTime), typeof(DaiesContainer), 
            new UIPropertyMetadata(DateTime.Now));
    
        public DateTime Date
        {
            get { return (DateTime)GetValue(DateProperty); }
            set
            {
                SetValue(DateProperty, value);
            }
        }
    

    I then use it in my XAML:

    <ctrls:DaiesContainer  Date="{Binding Date, Mode=OneWay}"/>
    

    In my ViewModel, the get method of the Date property is called. But in my user control, Date property is not set to a value.