[英]What am I doing wrong? Using the value of an Dependency Property in constructor
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.
我想使用DP的值在构造函数中初始化一个对象。
The problem is that Month is always 0 (during construction time) which causes the wrong initialization of the ExpenseDetailPageDataModel. 问题在于,Month始终为0(在构建期间),这会导致ExpenseDetailPageDataModel的初始化错误。 Right after the constructor finished his work the value of variable Month changes to correct value (in this case 11).
构造函数完成工作后,变量Month的值立即更改为正确值(在本例中为11)。
FinanceItemViewControl is a custom user control. FinanceItemViewControl是一个自定义用户控件。
<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_Changed
event. MonthProperty_Changed
事件中。 Loaded
event: Loaded
事件: public FinanceItemViewControl()
{
this.InitializeComponent();
detailPageDataModel = new ExpenseDetailPageDataModel(Month);
this.Loaded += UserControl_Loaded;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Constructor: " + Month);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.