WPF TextBox中自动选择焦点上的所有文本

4
在WPF文本框中,如何在焦点上自动选择所有文本?

3
将文本从英语翻译成中文:复制自https://dev59.com/SHRB5IYBdhLWcg3wUVxd - CAD bloke
这个回答解决了您的问题吗?如何在 WPF TextBox 中自动选择所有文本? - StayOnTarget
3个回答

6

1
这对键盘有效,但如果您也想在鼠标上选择全部,则无效。它会选择所有内容,然后鼠标抬起事件会取消选择。 - Jonathan Allen
3
这在WPF中是有意而为之的。通常,如果用户点击文本框,那就是为了定位插入符号。不过,我的博客文章底部有一条评论包含处理鼠标点击的代码。希望这能有所帮助。 - Matt Hamilton
1
当使用DevExoress控件来开发WPF应用程序时,它会变得更加容易。您可以使用TextEditBase.SelectAllOnKeyboardFocus属性来选择特定控件或者在应用于某些控件的样式中进行更一般的设置。 - Youp Bernoulli

4

基于Judah Himango在WinForms中的答案。这并不完美,但足够好用了。

使WinForms TextBox的行为类似于您的浏览器地址栏

Public Class GenericTextboxBehavior : Inherits Behavior(Of Windows.Controls.TextBox)

    Private WithEvents m_Target As TextBox
    Private alreadyFocused As Boolean

    Protected Overrides Sub OnAttached()
        If Not DesignerProperties.GetIsInDesignMode(AssociatedObject) Then
            m_Target = AssociatedObject
        End If
    End Sub

    Protected Overrides Sub OnDetaching()
        If Not DesignerProperties.GetIsInDesignMode(AssociatedObject) Then
            m_Target = Nothing
        End If
    End Sub

    Private Sub m_Target_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles m_Target.GotFocus
        Debug.WriteLine("LeftButton: " & Input.Mouse.LeftButton.ToString)
        Debug.WriteLine("MiddleButton: " & Input.Mouse.MiddleButton.ToString)
        Debug.WriteLine("RightButton: " & Input.Mouse.RightButton.ToString)
        Debug.WriteLine("XButton1: " & Input.Mouse.XButton1.ToString)
        Debug.WriteLine("XButton2: " & Input.Mouse.XButton2.ToString)


        If Input.Mouse.LeftButton = MouseButtonState.Released And Input.Mouse.MiddleButton = MouseButtonState.Released And Input.Mouse.RightButton = MouseButtonState.Released And Input.Mouse.XButton1 = MouseButtonState.Released And Mouse.XButton2 = MouseButtonState.Released Then
            m_Target.SelectAll()
            alreadyFocused = True
            Debug.WriteLine("GotFocus --> Select All")
        Else
            Debug.WriteLine("GotFocus " & alreadyFocused)
        End If
    End Sub

    Private Sub m_Target_LostFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles m_Target.LostFocus
        alreadyFocused = False
        Debug.WriteLine("LostFocus " & alreadyFocused)

    End Sub

    Private Sub m_Target_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles m_Target.PreviewMouseUp
        If Not alreadyFocused And m_Target.SelectionLength = 0 Then
            alreadyFocused = True
            m_Target.SelectAll()
            Debug.WriteLine("MouseUp --> Select All")
        Else
            Debug.WriteLine("MouseUp " & alreadyFocused)

        End If
    End Sub
End Class

编辑

#Region "Boilerplate for XAML Attached Properties"
Public Shared IsEnabledProperty As DependencyProperty = DependencyProperty.RegisterAttached("IsEnabled", GetType(Boolean), GetType(SelectAllTextboxBehavior), New FrameworkPropertyMetadata(False, AddressOf OnIsEnabledChanged))

Public Shared Function GetIsEnabled(ByVal uie As DependencyObject) As Boolean
    Return CBool(uie.GetValue(IsEnabledProperty))
End Function

Public Shared Sub SetIsEnabled(ByVal uie As DependencyObject, ByVal value As Boolean)
    uie.SetValue(IsEnabledProperty, value)
End Sub


Public Shared Sub OnIsEnabledChanged(ByVal dpo As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    Dim uie = TryCast(dpo, UIElement)
    If uie Is Nothing Then Return

    Dim behaviors = Interaction.GetBehaviors(uie)
    Dim existingBehavior = TryCast(behaviors.FirstOrDefault(Function(b) b.GetType() = GetType(SelectAllTextboxBehavior)), SelectAllTextboxBehavior)
    If CBool(e.NewValue) = False And existingBehavior IsNot Nothing Then
        behaviors.Remove(existingBehavior)
    Else
        behaviors.Add(New SelectAllTextboxBehavior)
    End If
End Sub
#End Region

0

来自Tortuga Sails的C#版本

using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using i = System.Windows.Interactivity;


namespace Tortuga.Sails
{


    /// <summary>
    /// This behavior/attached property causes all of the text in the textbox to be automatically selected when the user tabs into the control. Optionally, it also selects the text when the user clicks on it with the mouse.
    /// </summary>
    /// <remarks>
    /// 
    /// xmlns:s="clr-namespace:Tortuga.Sails;assembly=Tortuga.Sails"
    /// xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    /// 
    /// Attached Propety Syntax: 
    /// 
    /// s:SelectAllTextBoxBehavior.IsEnabled="True" 
    /// s:SelectAllTextBoxBehavior.SelectOnMouseClick="True"
    /// 
    /// Behaviors syntax
    /// 
    /// &lt;i:Interaction.Behaviors&gt;
    ///     &lt;s:SelectAllTextBoxBehavior OnMouseClick = "True" /&gt;
    /// &lt;/ i:Interaction.Behaviors&gt;
    /// 
    /// </remarks>
    public class SelectAllTextBoxBehavior : i.Behavior<TextBox>
    {
        bool m_AlreadyFocused;
        public bool OnMouseClick { get; set; }

        /// <summary>
        /// Called after the behavior is attached to an AssociatedObject.
        /// </summary>
        /// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks>
        protected override void OnAttached()
        {
            if (!DesignerProperties.GetIsInDesignMode(AssociatedObject))
            {
                AssociatedObject.GotFocus += Target_GotFocus;
                AssociatedObject.PreviewMouseUp += Target_MouseUp; //Need PreviewMouseUp or it can be swallowed by a child control
                AssociatedObject.LostFocus += Target_LostFocus;
            }
            base.OnAttached();
        }

        /// <summary>
        /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
        /// </summary>
        /// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks>
        protected override void OnDetaching()
        {
            if (!DesignerProperties.GetIsInDesignMode(AssociatedObject))
            {
                AssociatedObject.GotFocus -= Target_GotFocus;
                AssociatedObject.PreviewMouseUp -= Target_MouseUp;
                AssociatedObject.LostFocus -= Target_LostFocus;
            }
            base.OnDetaching();
        }

        private void Target_GotFocus(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("LeftButton: " + Mouse.LeftButton);
            Debug.WriteLine("MiddleButton: " + Mouse.MiddleButton);
            Debug.WriteLine("RightButton: " + Mouse.RightButton);
            Debug.WriteLine("XButton1: " + Mouse.XButton1);
            Debug.WriteLine("XButton2: " + Mouse.XButton2);
            if (Mouse.LeftButton == MouseButtonState.Released & Mouse.MiddleButton == MouseButtonState.Released & Mouse.RightButton == MouseButtonState.Released & Mouse.XButton1 == MouseButtonState.Released & Mouse.XButton2 == MouseButtonState.Released)
            {
                AssociatedObject.SelectAll();
                m_AlreadyFocused = true;
                Debug.WriteLine("GotFocus --> Select All");
            }
            else
            {
                Debug.WriteLine("GotFocus " + m_AlreadyFocused);
            }
        }

        void Target_LostFocus(object sender, RoutedEventArgs e)
        {
            m_AlreadyFocused = false;
            Debug.WriteLine("LostFocus " + m_AlreadyFocused);
        }

        void Target_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (!m_AlreadyFocused & AssociatedObject.SelectionLength == 0 && OnMouseClick)
            {
                m_AlreadyFocused = true;
                AssociatedObject.SelectAll();
                Debug.WriteLine("MouseUp --> Select All");
            }
            else
            {
                Debug.WriteLine("MouseUp " + m_AlreadyFocused + " OnMouse: " + OnMouseClick);
            }
        }

        #region "Boilerplate for XAML Attached Properties"

        public static DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(SelectAllTextBoxBehavior), new FrameworkPropertyMetadata(false, OnIsEnabledChanged));

        public static DependencyProperty SelectOnMouseClickProperty = DependencyProperty.RegisterAttached("SelectOnMouseClick", typeof(bool), typeof(SelectAllTextBoxBehavior), new FrameworkPropertyMetadata(false, OnSelectOnMouseClickChanged));

        public static bool GetIsEnabled(DependencyObject uie)
        {
            return (bool)(uie.GetValue(IsEnabledProperty));
        }

        public static bool GetSelectOnMouseClick(DependencyObject uie)
        {
            return (bool)(uie.GetValue(SelectOnMouseClickProperty));
        }

        public static void SetIsEnabled(DependencyObject uie, bool value)
        {
            uie.SetValue(IsEnabledProperty, value);
        }
        public static void SetSelectOnMouseClick(DependencyObject uie, bool value)
        {
            uie.SetValue(SelectOnMouseClickProperty, value);
        }

        static void OnIsEnabledChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e)
        {
            var uie = dpo as UIElement;
            if (uie == null)
                return;

            var behaviors = i.Interaction.GetBehaviors(uie);
            var existingBehavior = behaviors.FirstOrDefault(b => b.GetType() == typeof(SelectAllTextBoxBehavior)) as SelectAllTextBoxBehavior;



            if ((bool)e.NewValue == false && existingBehavior != null)
            {
                behaviors.Remove(existingBehavior);
            }
            else if ((bool)e.NewValue == true && existingBehavior == null)
            {
                behaviors.Add(new SelectAllTextBoxBehavior() { OnMouseClick = GetSelectOnMouseClick(dpo) });
            }
        }

        static void OnSelectOnMouseClickChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e)
        {
            var uie = dpo as UIElement;
            if (uie == null)
                return;

            var behaviors = i.Interaction.GetBehaviors(uie);
            var existingBehavior = behaviors.FirstOrDefault(b => b.GetType() == typeof(SelectAllTextBoxBehavior)) as SelectAllTextBoxBehavior;

            if (existingBehavior != null)
            {
                existingBehavior.OnMouseClick = (bool)e.NewValue;
            }
            else if ((bool)e.NewValue == true && existingBehavior == null)
            {
                SetIsEnabled(dpo, true);
                behaviors.Add(new SelectAllTextBoxBehavior() { OnMouseClick = true });
            }


        }
        #endregion
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接