#11934·Avalonia

Generate properties for templates using TemplatePartAttribute

Author: maxkatz6Created Mar 23, 2022Updated Sep 17, 2026
Labelsenhancementapi-needs-review

There is a new attribute ported from WPF. It will be useful to have optional code generation for "parts" of templates. As an example, user code:

csharp
[TemplatePart("PART_TextPresenter", typeof(TextPresenter))]
public partial class TextBox
{
    protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
            
        if (IsFocused)
        {
            TextPresenter?.ShowCaret(); // TextPresenter is generated
        }
    }
}

Additional generated code, adds new property and sets value to it:

csharp
#nullable enable
public partial class TextBox
{
    private TextPresenter? TextPresenter { get; set; }

    static TextBox()
    {
         TemplateAppliedEvent.AddClassHandler<TextBox>((control, args) =>
         {
             control.TextPresenter = args.NameScope.Get<TextPresenter>("PART_TextPresenter");
         });
    }
}

Problems:

  1. Only one static ctor can be created for class, if we want to handle TemplateAppliedEvent to fill these properties.
  2. Only one override of OnTemplateApplied method is possible, if we want to use it to fill these properties.

Which means, we most likely will need to modify Avalonia to add yet another way to read namescope after template was applied.