我做错了什么?在构造函数中使用依赖项属性的值



我在使用依赖属性时遇到了一些问题。我想使用 DP 的值来初始化构造函数中的对象。

问题是 Month 始终为 0(在施工期间),这会导致 ExpenseDetailPageDataModel 的错误初始化。在构造函数完成他的工作后,变量 Month 的值立即更改为正确的值(在本例中为 11)。

FinanceItemViewControl 是一个自定义用户控件。

<common:FinanceItemViewControl Grid.Column="2" Month="11"/>

Month 是一个依赖项属性,如下面的代码所示:

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);
...
        }

您不能将该逻辑放在构造函数中,因为正如您所注意到的,数据上下文尚未加载。 您可以执行以下两项操作之一:

  1. 将逻辑放在 MonthProperty_Changed 事件中。
  2. 使用控件的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);
}

最新更新