John Livermore
John Livermore

Reputation: 31313

UWP CalendarDatePicker GetTemplateChild call

The following class extends the UWP CalendarDatePicker...

public class MyDatePicker : CalendarDatePicker
{
    protected override void OnApplyTemplate()
    {
        _backgroundBorder = base.GetTemplateChild("Background") as Border;

        base.OnApplyTemplate();
    }
}

What does the GetTemplateChild("Background") call do? It returns a Border type evidently (this code is from a Microsoft Github repo), but what is Background? And where are these magic strings defined?

For example, if I were to extend a TimePicker in the same manner, what elements are available to me with the GetTemplateChild call for a class that extends TimePicker? And how do you figure this out?

I appreciate any pointers.

Upvotes: 0

Views: 79

Answers (1)

ardget
ardget

Reputation: 2651

In general, Control's UI is to be instantiated dynamically in runtime by applying ControlTemplate that is pre-defined in Style. "TemplateChild" is a XAML-Element* being used in the ControlTemplate. A certain TemplateChild has a hard-coded x:Name (=magic string). By calling GetTemplateChild() with the name parmeter, you can obtain access to the element.

The default Style to be applied to built-in Control can be found in generic.xaml. Inspecting the ControlTemplate in the Style for relevant Control, you'll find all the names that you can specify in GetTemplateChild calls.

*XAML-Element: UIElement (or other elements such as Brush, Transform, Storyboard, etc.)

Upvotes: 1

Related Questions