2011-08-22 69 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事件。