2

我在使用依赖属性时遇到了一些问题。我想使用 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);
...
        }
4

1 回答 1

8

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

  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);
}
于 2012-12-15T00:54:02.527 回答