maui icon indicating copy to clipboard operation
maui copied to clipboard

[Windows] Fix select-all Entry select logic

Open Foda opened this issue 1 year ago • 2 comments

Description of Change

Consider that you want to implement a "select all text on focus" function for an Entry field:

private void OnEntryFocused(object? sender, FocusEventArgs e)
{
    if (TextBox.Text != null)
    {
        TextBox.CursorPosition = 0;
        TextBox.SelectionLength = entry.Text.Length;
    }
}

Currently, this will work the first time the Entry is focused, but it won't work the second time.

The problem is caused by the following:

  • Entry gains focus
  • Cursor position and selection length are set, values propagate to WinUI TextBox
  • Entry is unfocused
  • Entry gains focus again
  • Cursor position and selection length are set, but the values are the same, so we don't set the values again on the WinUI TextBox
  • WinUI TextBox handles input event, moves cursor to where you click (note: the native WinUI TextBox seems to have special logic around canceling this logic if setting selection during an OnFocus event? this is where the issue comes from!)
  • WinUI control then propagates cursor position and selection length values to the Maui Entry, text is now unselected

The fix here is to just always ensure setting cursor position and selection length flows to the native WinUI TextBox control. A better solution might be adding a Select and SelectAll method to Entry, but for now this will work.

Foda avatar Jun 27 '24 22:06 Foda

/azp run

jsuarezruiz avatar Oct 23 '24 09:10 jsuarezruiz

Azure Pipelines successfully started running 3 pipeline(s).

azure-pipelines[bot] avatar Oct 23 '24 09:10 azure-pipelines[bot]

/rebase

Foda avatar Nov 18 '24 17:11 Foda

/rebase

Foda avatar Mar 12 '25 17:03 Foda