In WPF, you will declare XAML controls for code-behind use with TemplatePart, and then get a reference to those controls with GetTemplateChild.
How do you accomplish this in Avalonia UI?
CodePudding user response:
Set control Name inside template.
<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>
In override OnApplyTemplate use 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");
}
}
}