【问题标题】:GetTemplateChild / TemplatePart in Avalonia?Avalonia 中的 GetTemplateChild / TemplatePart?
【发布时间】:2021-12-27 00:00:03
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net xaml avaloniaui


    【解决方案1】:

    在模板中设置控件名称。

    <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>
    

    在覆盖 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");
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-14
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      相关资源
      最近更新 更多