【问题标题】:Select All Content of TextBox on GotFocus Event在 GotFocus 事件中选择 TextBox 的所有内容
【发布时间】:2012-05-11 04:57:00
【问题描述】:

我正在开发 WPF 应用程序,其中有一些显示美元金额的文本框。每当焦点出现在文本框上时,我只想选择文本框中的所有内容。

为了达到同样的效果,我在“GotFocus”事件中使用了文本框的 SelectAll() 方法,但它并没有按预期工作。

请告诉我如何才能发挥作用。谢谢

【问题讨论】:

    标签: .net wpf textbox wpf-controls focus


    【解决方案1】:

    在启动时,为文本框注册一个全局事件处理程序 例如

     EventManager.RegisterClassHandler(typeof(System.Windows.Controls.Primitives.TextBoxBase), UIElement.GotFocusEvent, new RoutedEventHandler(TextBoxBaseGotFocus));
    

    TextBoxBaseGotFocus 方法是这样的:

        private static void TextBoxBaseGotFocus(object sender, RoutedEventArgs e)
    {
         // Get the TextBoxBase
         var elem = sender as System.Windows.Controls.Primitives.TextBoxBase;
         if (elem != null)
         {
             elem.SelectAll();
         }
    }
    

    【讨论】:

      【解决方案2】:

      您可以为此创建附加行为并将其用于所需的文本框。此处详细说明了此方法-

      http://eladm.wordpress.com/2009/04/02/attached-behavior/

      此类行为的代码也可在 here 和 here 获得

      如果您希望应用程序中的所有文本框默认都具有此功能,请查看此处 -

      How to Select All Text in a WPF TextBox on Focus

      【讨论】:

        【解决方案3】:

        您是否尝试过处理 FocusableChanged 事件 http://msdn.microsoft.com/en-us/library/system.windows.uielement.focusablechanged.aspx

        您可以在 FocusableChanged 事件处理程序中检查 IsFocused。如果 IsFocused 为真,则可以调用 SelectAll 以下是伪代码

        textBox.FocusableChanged += (s,e) =>
        {
           if(textBox.IsFocused)
             testBox.SelectAll();
        }
        

        编辑1
        由于上述不起作用,您可以尝试 FocusManger.GetFocusedElement。
        determining-the-focused-element

        public DebugFocusedElementProxy()
        {
            var timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Tick += (o, ea) =>
            {
                var fe = FocusManager.GetFocusedElement();
                if (fe != null)
                {
                    var element = fe as FrameworkElement;
                    if (!string.IsNullOrEmpty(element.Name) &&
                         String.Equals(element.Name, textBox))
                    {
                        textBox.SelectAll();
                    }
                }
            };
            timer.Start();
        }
        

        //注意 textBox.SelectAll 可能需要在 Dispatcher Thread 上调用

        【讨论】:

        • 我尝试了上述方法,但在文件附加事件背后的代码中没有触发。
        • 如果这不起作用,丑陋的方法是使用 FocusManager.GetFocusedElement 和计时器事件(因为 FocusManageR 中没有事件)
        • 是的,这是使用 FocusManager.GetFocusedElement 的非常昂贵的方式,因为它需要线程。
        • 我可以使用文本框的样式绑定事件(GotKeyBoardFocus 和 MouseCapture)吗?
        • 感谢 Tilak,它对我有用。我在样式中使用了 EventSetter 来附加 GotKeyBoardFocus 和 MouseCapture 事件的处理程序。谢谢
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-27
        • 2014-12-27
        相关资源
        最近更新 更多