I’m having some problems with the usage of an Dependency Property. I would like to use the value of the DP to initialize an object in the constructor.
The problem is that Month is always 0 (during construction time) which causes the wrong initialization of the ExpenseDetailPageDataModel. Right after the constructor finished his work the value of variable Month changes to correct value (in this case 11).
FinanceItemViewControl is a custom user control.
<common:FinanceItemViewControl Grid.Column="2" Month="11"/>
Month is a Dependency Property as shown in the code below:
public sealed partial class FinanceItemViewControl : UserControl
{
...
public static readonly DependencyProperty MonthProperty = DependencyProperty.Register
(
"Month",
typeof(int),
typeof(FinanceItemViewControl),
new PropertyMetadata(
0, new PropertyChangedCallback(MonthProperty_Changed))
);
public int Month
{
get { return (int)GetValue(MonthProperty); }
set { SetValue(MonthProperty, value); }
}
#endregion
private static void MonthProperty_Changed(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
//TODO: trigger data reload
}
public FinanceItemViewControl()
{
this.InitializeComponent();
...
Debug.WriteLine("Constructor: " + Month);
detailPageDataModel = new ExpenseDetailPageDataModel(Month);
...
}
You can’t put that logic in the constructor because, as you noticed, the Data Context hasn’t loaded yet. You could do one of two things:
MonthProperty_Changedevent.Loadedevent: