【问题标题】:How to select all text in textbox when it gets focus获得焦点时如何选择文本框中的所有文本
【发布时间】:2014-11-05 01:54:23
【问题描述】:

在 Windows phone 中,如何在 TextBox 有焦点时选择 Textbox 中的所有文本?

我尝试设置文本框的获取焦点属性:

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox .SelectAll();
    }

我看到的是我看到所有文本都被选中了 1-2 秒,然后它返回光标模式(即 1 条闪烁线)。

【问题讨论】:

  • 您正在选择要复制的文本或进行某种操作,还是只想突出显示文本?
  • 我想在TextBox有焦点时选择要复制的文本。
  • 我希望所有的文本都被选中,这样当用户按下一个键时,比如 b,所有的文本都将消失并替换为 'b'。
  • 类似于 WP 中的键盘字典?
  • 所以这是使用... UWP 编程的?

标签: c# windows-phone-8.1


【解决方案1】:

我在 WPF 上遇到了同样的问题并设法解决了它。不知道你是否可以使用我使用的,但基本上你的代码看起来像:

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox .CaptureMouse()
    }

    private void TextBox_GotMouseCapture(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox.SelectAll();
    }

private void TextBox_IsMouseCaptureWithinChanged(object sender, RoutedEventArgs e)
    {
        TextBox textBox = (TextBox)sender;

        textBox.SelectAll();
    }

所有事件都连接到原始文本框。如果这对您不起作用,也许您可​​以用 CaptureTouch 替换 CaptureMouse(并使用适当的事件)。祝你好运!

【讨论】:

    【解决方案2】:

    你可以试试这段代码,

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            String sSelectedText = mytextbox.SelectedText;
        }
    

    如果用户点击选择后出现的复制图标,它将被复制,如果你想以编程方式进行,你可以试试这个

    DataPackage d = new DataPackage();
    d.SetText(selectedText);
    Clipboard.SetContent(d);
    

    我建议在其他事件中进行复制而不是在 gotfocus 中进行复制,因为这将在用户点击文本字段后立即触发,因此当没有实际输入文本时将调用此方法。

    【讨论】:

    • 谢谢。如果我只想选择所有文本怎么办? (即所有以选定颜色作为背景的文本)当用户再次单击它时,它会返回光标模式(即只是一个“|”)?
    【解决方案3】:
    protected override void OnStartup(StartupEventArgs e)
    {
        //works for tab into textbox
        EventManager.RegisterClassHandler(typeof(TextBox),
            TextBox.GotFocusEvent,
            new RoutedEventHandler(TextBox_GotFocus));
        //works for click textbox
        EventManager.RegisterClassHandler(typeof(Window),
            Window.GotMouseCaptureEvent,
            new RoutedEventHandler(Window_MouseCapture));
    
        base.OnStartup(e);
    }
    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        (sender as TextBox).SelectAll();
    }
    
    private void Window_MouseCapture(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
             textBox.SelectAll(); 
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 2010-11-13
      • 2014-03-03
      • 2014-05-29
      • 2011-03-13
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多