开发者

When is data binding in WPF evaluated?

开发者 https://www.devze.com 2023-03-30 01:58 出处:网络
I am binding the CustomerID property in my custom control to the same property in an ancestor. The ancesor is a TopLevelControl.

I am binding the CustomerID property in my custom control to the same property in an ancestor. The ancesor is a TopLevelControl.

I set up the binding in the child control's constructor and access the property in OnApplyTemplate() where I also do some other initialization. But it seems to me that the binding is not evaluated when OnApplyTemplate() is called. Why and when is it updated with the binding?

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


The reason is that controls are not added to the visual tree until after they are initialized. Since you are binding the control to an ancestor, the data source (the ancestor) doesn't exist (from the control's perspective) until the control has been added to the visual tree (after ApplyTemplate is done).

I'd recommend moving that code to the Load event.

0

精彩评论

暂无评论...
验证码 换一张
取 消