How to Get the Control in Default Template of Custom Control

By Michael Detras

When creating a custom control, we usually define a default template for it. Sometimes, we name the controls in the default template so we can access them later on and probably do something with it later in code.

Let's say we have some control where its default template contain an Ellipse. On the OnApplyTemplate method, we can get the Ellipse using the GetTemplateChild method. Here is a basic example.

[TemplatePart(Name = "PART_Ellipse", Type = typeof(Ellipse))]
public class DerivedControl : Control
{
private Ellipse ellipse;

    static DerivedControl()
    {
         DefaultStyleKeyProperty.OverrideMetadata(typeof(DerivedControl), new FrameworkPropertyMetadata(typeof(DerivedControl)));
    }

    public override void OnApplyTemplate()
    {
         base.OnApplyTemplate();                      

        ellipse = (DataGrid)base.GetTemplateChild("PART_Ellipse");
        if (ellipse!= null)
        {
// Do something with Ellipse
}
}

Related FAQs

Usually, we use XAML to specify templates for our controls like Button and TextBox. However, there may be some times when we need to do it programmatically or via code.
How to Get the Control in Default Template of Custom Control  (1059 Views)