在阿瓦隆尼亚获取TemplateChild / TemplatePart?

Eti*_*and 3 .net c# xaml avaloniaui

在 WPF 中,您将使用 TemplatePart 声明用于代码隐藏的 XAML 控件,然后使用 GetTemplateChild 获取对这些控件的引用。

如何在 Avalonia UI 中实现这一点?

Wie*_*tés 5

在模板内设置控件名称。

<Styles xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:controls="using:Sample.Controls">
  <Style Selector="controls|TestControl">
    <Setter Property="Template">
      <ControlTemplate>
        <TextBlock Name="PART_TextBlock" Text="Templated Control" />
      </ControlTemplate>
    </Setter>
  </Style>
</Styles>
Run Code Online (Sandbox Code Playgroud)

在重写 OnApplyTemplate 中使用 e.NameScope.Find(...)

using Avalonia.Controls;
using Avalonia.Controls.Primitives;

namespace Sample.Controls
{
    public class TestControl : TemplatedControl
    {
        protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
        {
            base.OnApplyTemplate(e);

            var tb = e.NameScope.Find<TextBlock>("PART_TextBlock");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)