自动选择焦点Xamarin上的所有文本

时间:2015-01-28 14:04:56

标签: c# xaml xamarin.forms onfocus

如何在Entry,Editor,Label中自动选择焦点上的所有文本?使用跨平台。

Quantity.IsFocused = true; 

没有工作:(

5 个答案:

答案 0 :(得分:6)

在MainActivity中添加

public class MyEntryRenderer : EntryRenderer
{
    protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged (e);
        if (e.OldElement == null) {
            var nativeEditText = (global::Android.Widget.EditText)Control;
            nativeEditText.SetSelectAllOnFocus (true);
        }
    }
}

并向顶部添加:

[assembly: ExportRenderer (typeof (Entry), typeof (MyEntryRenderer))]

答案 1 :(得分:4)

如其他答案中所述,如果您使用Xamarin Forms 4.2+,则可以使用CursorPosition和SelectionLength属性。但是,您需要确保在主线程上调用它,否则它将不起作用:

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
    });
}

答案 2 :(得分:3)

1。添加焦点事件.cs

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

设置焦点

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

XAML代码

    <Entry x:Name="txt" Text="155134343" Focused="Txt_Focussed"  />

答案 3 :(得分:2)

UWP自定义条目渲染器可能是......

using System.ComponentModel;

using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;

[assembly: ExportRenderer(typeof(Entry), typeof(myApp.UWP.ExtendedEntryRenderer))]
namespace myApp.UWP
{
    public class ExtendedEntryRenderer : EntryRenderer
    {
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == nameof(Entry.IsFocused)
                && Control != null && Control.FocusState != Windows.UI.Xaml.FocusState.Unfocused)
                Control.SelectAll();
        }
    }
}

答案 4 :(得分:1)

在我的情况下,要做出@SAIJAN KP的答案,我制作了Focused处理程序async,并等待了一段时间以等待光标出现在Entry上:

    private async void Entry_Focused(object sender, FocusEventArgs e)
    {
        await Task.Delay(100);
        entryTest.CursorPosition = x;
        entryTest.SelectionLength = y;
    }

XAML

<Entry x:Name="entryTest" Text="155134343" Focused="Entry_Focused"  />
相关问题