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

Ibr*_*him 4 c# xaml onfocus xamarin.forms

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

Quantity.IsFocused = true; 
Run Code Online (Sandbox Code Playgroud)

没工作:(

SAI*_* KP 11

1.添加焦点事件.Cs

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

设置焦点

protected override void OnAppearing()
{
    base.OnAppearing();
    txt.Focus();
}
Run Code Online (Sandbox Code Playgroud)

XAML 代码

<Entry x:Name="txt" Text="155134343" Focused="Txt_Focussed" />
Run Code Online (Sandbox Code Playgroud)

  • 需要 Xamarin.Form (4.2.0.709249) (2认同)
  • 正如其他答案中提到的,要选择文本,请确保将代码包装在“Dispatcher.BeginInvokeOnMainThread”中,否则它将不起作用。另一件需要注意的事情是,如果用户在渲染后很早就点击“txt.Text”,则它可能为空。确保处理好它以防止崩溃。 (2认同)

kid*_*ley 8

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

XAML

<Entry x:Name="MyEntry" Focused="MyEntry_Focused"  />
Run Code Online (Sandbox Code Playgroud)

C#

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

  • ToolmakerSteve/BobSammers:这个主题感觉在文档中被掩盖了一些。也许假设是因为它是多线程的,所以它应该是显而易见的,谁知道呢。我也通过“艰难的方式”了解了这些细节,这就是为什么我最初添加了澄清答案,所以我感谢所有的问题/讨论:) (2认同)

Ibr*_*him 7

在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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并添加到顶部:

[assembly: ExportRenderer (typeof (Entry), typeof (MyEntryRenderer))]
Run Code Online (Sandbox Code Playgroud)

  • 那么UWP怎么样我可以为UWP平台创建这个自定义渲染器 (2认同)
  • @Darran - `SetNativeControl(Control)` 是多余的;它本质上是在说`Control = Control;`。只需执行`if (Control != null) Control.SetSelectAllOnFocus(true);` 或者在c#6 中可以将`if` 测试简化为“null check”: 简化为:`Control?.SetSelectAllOnFocus(true);` (2认同)