Автоматически выбирать весь текст в фокусе в WPF TextBox

Как вы автоматически выбираете весь текст в фокусе в текстовых блоках WPF?

Ответ 1

На основании ответа Иуды Химанго для 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

EDIT

#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

Ответ 3

Версия С# от Tortuga Sails

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