Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically select all text on focus Xamarin

How to automatically select all text on focus in Entry,Editor,Label? Use Cross Platforms.

Quantity.IsFocused = true; 

No work :(

like image 239
Ibrahim Avatar asked Jan 28 '15 14:01

Ibrahim


2 Answers

As mentioned in other answers, if you are using Xamarin Forms 4.2+, you can use the CursorPosition and SelectionLength properties. However, you need to make sure you invoke on the Main/UI thread as all direct manipulation of UI elements must be done there. The app will very likely crash when deployed to a device without doing so, even if it appears to run fine in a simulator.

XAML

<Entry x:Name="MyEntry" Focused="MyEntry_Focused"  />

C#

private void MyEntry_Focused(object sender, FocusEventArgs e)
{
    Dispatcher.BeginInvokeOnMainThread(() =>
    {
        MyEntry.CursorPosition = 0;
        MyEntry.SelectionLength = MyEntry.Text != null ? MyEntry.Text.Length : 0
    });
}

For Xamarin.Forms, you can also use Device.BeginInvokeOnMainThread() rather than Dispatcher. If you're using Xamarin Essentials, there is also MainThread.BeginInvokeOnMainThread() (which does the same as Device.BeginInvokeOnMainThread()).

Xamarin.Forms has a method called Device.BeginInvokeOnMainThread(Action) that does the same thing as MainThread.BeginInvokeOnMainThread(Action). While you can use either method in a Xamarin.Forms app, consider whether or not the calling code has any other need for a dependency on Xamarin.Forms. If not, MainThread.BeginInvokeOnMainThread(Action) is likely a better option.

like image 68
kiddailey Avatar answered Nov 03 '22 07:11

kiddailey


1.Add Focused Event.Cs

protected  void Txt_Focussed(object sender, FocusEventArgs e)
{
    txt.CursorPosition = 0;
    txt.SelectionLength = txt.Text.Length;
}

Set focus

protected override void OnAppearing()
{
    base.OnAppearing();
    txt.Focus();
}

XAML Code

<Entry x:Name="txt" Text="155134343" Focused="Txt_Focussed" />
like image 12
SAIJAN KP Avatar answered Nov 03 '22 08:11

SAIJAN KP