Search code examples
c#wpfbindinguser-controlsdependency-properties

UserControl DependencyProperty Value always 0 when bound to ViewModel Property


I have a simple UserControl with 3 Dependency Properties. Day, Month and Year.

public static readonly DependencyProperty DayProperty = DependencyProperty.Register("Day", typeof(int), typeof(BoardPanel), new FrameworkPropertyMetadata(0));
public int Day
{
    get { return (int)GetValue(DayProperty); }
    set { SetValue(DayProperty, value); }
}

public static readonly DependencyProperty MonthProperty = DependencyProperty.Register("Month", typeof(int), typeof(BoardPanel), new FrameworkPropertyMetadata(0));
public int Month
{
    get { return (int)GetValue(MonthProperty); }
    set { SetValue(MonthProperty, value); }
}

public static readonly DependencyProperty YearProperty = DependencyProperty.Register("Year", typeof(int), typeof(BoardPanel), new FrameworkPropertyMetadata(0));
public int Year
{
    get { return (int)GetValue(YearProperty); }
    set { SetValue(YearProperty, value); }
}

and another string Property DayOfWeek.

public string DayOfWeek
{
    get { return new DateTime(Year, Month, Day).DayOfWeek.ToString(); }
}

The Day and DayOfWeek Properties are bound to two Textboxes in XAML.

When using this UserControl and setting all values manually everything works fine.

<c:DatePanel Day="1" Month="4" Year="2022"/>

UserControl with static values

When binding these to Properties from my ViewModel however it throws an exeption and shows that Month and Year are 0.

<c:DatePanel Day="2" Month="{Binding Month}" Year="{Binding Year}"/>

System.ArgumentOutOfRangeException: "Year, Month, and Day parameters describe an un-representable DateTime."

UserControl with bound values

I'm quite new to this topic but I'd assume that the binding is not resolved yet at the time the control gets initialized or something?

How would you do this correctly?


Solution

  • Apparently your bindings don't work.

    The reason is that you have explicitly set the DataContext of the UserControl to itself which effectively prevents it from inheriting the DataContext from its parent element and bind to the properties of it.

    Don't do this:

    this.DataContext = this;
    

    You should also raise a property changed event for the DayOfWeek property whenever the Day, Month or Year property is set but I see no PropertyChangedCallback in your code.