OXO
OXO

Reputation: 1098

Select all Text in Entry when Focused

In my .NET MAUI App, I wanted to select the entire Text when an Entry is focused so that the Input can be made quicker without having to delete the initial input.

Therefore, I added the following code:

XAML

<Entry Text="{Binding Min, Mode=TwoWay}" Focused="Entry_Focused" />

Code-Behind

private void Entry_Focused(object sender, FocusEventArgs e)
{
    var entry = sender as Entry;

    entry.CursorPosition = 0;
    entry.SelectionLength = entry.Text == null ? 0 : entry.Text.Length;
}

In my Pixel 5 - API 33 (Android 13.0 - API 33) Emulator it behaves like that when I click my Entry with the mouse.

enter image description here

When I move ahead with Tab (which the user does not have) it behaves correctly as you can see here

enter image description here

What is the correct way to solve this issue so that it behaves like on the second screenshot when a user clicks into the Entry and sets the focus?

Upvotes: 6

Views: 3301

Answers (1)

ToolmakerSteve
ToolmakerSteve

Reputation: 21357

Changes to cursor do not work correctly, when inside Android’s Focused event. This is true regardless of language (happens for native Java apps also).

The fix is to queue the changes, so they happen after the method returns. This can be done with Dispatch:

Dispatcher.Dispatch( () =>
{
    // your code here
});

In your case, put all the code of Entry_Focused inside the Dispatch.

Upvotes: 9

Related Questions