2011-08-22 67 views
0

我将自定义控件中的CustomerID属性绑定到祖先中的相同属性。该ancesor是一个TopLevelControl。什么时候评估WPF中的数据绑定?

我在子控件的构造函数中设置绑定并访问OnApplyTemplate()中的属性,我也在其中进行一些其他初始化。但是在我看来,在调用OnApplyTemplate()时不会评估绑定。为什么以及何时更新绑定?

我CustomChildControl:

public String CustomerID { 
    get{ return (bool) base.GetValue(CustomerIDProperty);} 
    set{ base.SetValue(CustomerIDProperty, value);} 
} 

public CustomChildControl() 
{ 
    binding = new Binding("CustomerID") 
    { 
     RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(TopLevelControl),1) 
    }; 
    SetBinding(CustomerIDProperty, binding); 
} 

override OnApplyTemplate(){ 

    base.OnApplyTemplate(); 
    // CustomerID is null here... why? 

    Initialize(CustomerID); 
} 
+1

如果你回过头来回答并回答一些问题,你更有可能得到答复 - 你有9个未解决的问题。 –

回答

4

的原因是,控件不会添加到Visual树,直到它们被初始化之后。由于您将控件绑定到祖先,因此直到控件添加到可视化树中(ApplyTemplate完成后),数据源(祖先)才会存在(从控件的角度来看)。

我建议将该代码移动到Load事件。