Avalonia: SelectAll in a TextBox on GotFocus


Overview

I was attempting to select all of the text on a TextBox in an Avalonia 11 app and I was receiving inconsistent results where SelectAll would work sometimes and not other times. The issue ended up being the order in which events were firing creating a race condition. In order to ensure the SelectAll fired and worked consistently I ran it through a Dispatcher post:

XAML

<TextBox Focusable="True" GotFocus="TextInput_GotFocus">
</TextBox>

C#

private void TextInput_GotFocus(object? sender, GotFocusEventArgs e)
{
		var textBox = sender as TextBox;

		if (textBox == null)
		{
				return;
		}

		// Defer the SelectAll() method call using the dispatcher
		Dispatcher.UIThread.Post(() =>
		{
        textBox.SelectAll();
		});
}