Initializing controls within your WPF custom control template

Sometimes your custom control is a composite control where your template contains multiple WPF controls.
If you want to initialize those controls from code this cannot be done in the constructor of your custom control.
To do so, there is an override of the OnApplyTemplate method which is the best place to do Initialization.

Example:

public override void OnApplyTemplate() { Button myButton = this.Template.FindName("MyButton", this) as Button; myButton.Click +=new RoutedEventHandler(myButton_Click); myButton.Content = "Initialized"; }

Related posts