Search code examples
c#wpftextbox

Why does WPF textbox not support triple-click to select all text


is there a reason why a WPF textbox does not support triple-click behaviour like most modern UIs these days do?

By "triple click", I mean: double clicking a line of text in a textbox selects a single word, while triple clicking selects the whole line.

Is there an attribute that can be applied to textbox, or another workaround? Is there any chance Microsoft will implement it as default behaviour for a WPF textbox?


Solution

  • As already answered, you can implement that manually. But you don't want to do that for each textbox in your application. So you can implement attached property and set it in style, like this:

    public static class TextBoxBehavior {
        public static readonly DependencyProperty TripleClickSelectAllProperty = DependencyProperty.RegisterAttached(
            "TripleClickSelectAll", typeof(bool), typeof(TextBoxBehavior), new PropertyMetadata(false, OnPropertyChanged));
    
        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            var tb = d as TextBox;
            if (tb != null) {
                var enable = (bool)e.NewValue;
                if (enable) {
                    tb.PreviewMouseLeftButtonDown += OnTextBoxMouseDown;
                }
                else {
                    tb.PreviewMouseLeftButtonDown -= OnTextBoxMouseDown;
                }
            }
        }
    
        private static void OnTextBoxMouseDown(object sender, MouseButtonEventArgs e) {
            if (e.ClickCount == 3)
            {
                ((TextBox)sender).SelectAll();
            }
        }
    
        public static void SetTripleClickSelectAll(DependencyObject element, bool value)
        {
            element.SetValue(TripleClickSelectAllProperty, value);
        }
    
        public static bool GetTripleClickSelectAll(DependencyObject element) {
            return (bool) element.GetValue(TripleClickSelectAllProperty);
        }
    }
    

    Then create style somewhere (for example in application resources in App.xaml):

    <Application.Resources>
        <Style TargetType="TextBox">
            <Setter Property="local:TextBoxBehavior.TripleClickSelectAll"
                    Value="True" />
        </Style>
    </Application.Resources>
    

    Now all your textboxes will automatically have this triple-click behavior.