我将自定义控件中的CustomerID属性绑定到祖先中的同一属性。 ancesor是一个TopLevelControl。
我在子控件的构造函数中设置了绑定,并在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);
}
答案 0 :(得分:4)
原因是控件在初始化之前不会添加到可视树中。由于您将控件绑定到祖先,因此数据源(祖先)不存在(从控件的角度来看),直到将控件添加到可视树中(在ApplyTemplate完成之后)。
我建议将该代码移至Load事件。