【问题标题】:UWP CalendarDatePicker GetTemplateChild callUWP CalendarDatePicker GetTemplate子调用
【发布时间】:2020-04-19 08:13:10
【问题描述】:

以下类扩展了 UWP CalendarDatePicker...

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

        base.OnApplyTemplate();
    }
}

GetTemplateChild("Background") 调用有什么作用?它显然返回一个Border 类型(此代码来自Microsoft Github 存储库),但Background 是什么?这些魔术字符串是在哪里定义的?

例如,如果我要以相同的方式扩展 TimePicker,那么对于扩展 TimePicker 的类的 GetTemplateChild 调用,我可以使用哪些元素?你是怎么解决这个问题的?

感谢任何指点。

【问题讨论】:

  • 那个魔法字符串是一个硬编码的 x:Name 给 TemplateChild(=在 ControlTemplate 中使用的 UIElement)。检查generic.xaml 中定义的默认样式,您会发现可以在 GetTemplateChild 调用中指定的所有名称。
  • 非常感谢。如果您将此作为答案发布,我会将其标记为这样!

标签: uwp


【解决方案1】:

一般来说,Control 的 UI 将在运行时通过应用 Style 中预定义的 ControlTemplate 动态实例化。 “TemplateChild”是在 ControlTemplate 中使用的 XAML 元素*。某个 TemplateChild 有一个硬编码的 x:Name(=magic 字符串)。通过使用名称参数调用 GetTemplateChild(),您可以获得对元素的访问权限。

可以在generic.xaml 中找到要应用于内置控件的默认样式。检查相关控件的样式中的 ControlTemplate,您会发现可以在 GetTemplateChild 调用中指定的所有名称。

*XAML-Element:UIElement(或其他元素,如Brush、Transform、Storyboard等)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2018-07-31
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多