Pavel Sumarokov
Pavel Sumarokov

Reputation: 212

How to force keyboard input focus in Avalonia form

enter image description here

For instance I have a simple form with just one TextBox. When this form is shown, input box upon it doesn't have keyboard focus, so, working in the program I'm creating, in this case I stupidly have to press Tab key to enter my box. How to avoid this and get my TextBox keyboard-focused when form appears?

AXAML:

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
        x:Class="SpaceDunyal.Forms.Window1"
        Title="MyWindow">
    <StackPanel Margin="10">
        <TextBox Name="MyInput" Watermark="Input yor text"/>
    </StackPanel>
</Window>

C#:

using Avalonia.Controls;

namespace SpaceDunyal.Forms
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            MyInput.Focus(); // No effect
        }
    }
}

Upvotes: 2

Views: 1618

Answers (1)

radoslawik
radoslawik

Reputation: 1202

You have to call the Focus() function only after MyInput control is added to the visual tree:

MyInput.AttachedToVisualTree += (s, e) => MyInput.Focus();

Upvotes: 3

Related Questions