![](/img/trans.png)
[英]What am I doing wrong in this binding of a dependency property in the code behind (of a view) to a property its viewmodel?
[英]What am I doing wrong? Using the value of an Dependency Property in constructor
我在使用依赖项属性时遇到一些问题。 我想使用DP的值在构造函数中初始化一个对象。
问题在于,Month始终为0(在构建期间),这会导致ExpenseDetailPageDataModel的初始化错误。 构造函数完成工作后,变量Month的值立即更改为正确值(在本例中为11)。
FinanceItemViewControl是一个自定义用户控件。
<common:FinanceItemViewControl Grid.Column="2" Month="11"/>
月是一个依赖项属性,如下面的代码所示:
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);
...
}
您不能将该逻辑放入构造函数中,因为您注意到,数据上下文尚未加载。 您可以执行以下两项操作之一:
MonthProperty_Changed
事件中。 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.