Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in XAML to select all text in textbox when double clicked?

Tags:

c#

wpf

xaml

Is there a way to highlight all text in textbox purely through XAML, or does it have to be done in the Xaml.cs

Thanks!

like image 763
KeyboardFriendly Avatar asked Apr 16 '13 15:04

KeyboardFriendly


2 Answers

This is what you are going to do:

First, add DoubleClickBehavior.cs class to your Project.

class DoubleClickBehavior : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            AssociatedObject.MouseDoubleClick += AssociatedObjectMouseDoubleClick;
            base.OnAttached();
        }

        protected override void OnDetaching()
        {
            AssociatedObject.MouseDoubleClick -= AssociatedObjectMouseDoubleClick;
            base.OnDetaching();
        }

        private void AssociatedObjectMouseDoubleClick(object sender, RoutedEventArgs routedEventArgs)
        {
            AssociatedObject.SelectAll();
        }
    }

Then in .xaml, add this behavior to your TextBox:

<TextBox>
        <i:Interaction.Behaviors>
            <local:DoubleClickBehavior/>
        </i:Interaction.Behaviors>
</TextBox>

You need to add two namepsaces to your .xaml to use your behavior. (The name of my project was WpfApplication1, so you will probably need to change that):

 xmlns:local ="clr-namespace:WpfApplication1" 
 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

That's it. Also you need System.Windows.Interactivity.dll to use the Behavior class.

You can download it from the Nuget Package Manager.

like image 162
Farhad Jabiyev Avatar answered Nov 13 '22 22:11

Farhad Jabiyev


With a TextBox, you can add the PreviewMouseDoubleClick event.

<TextBox DockPanel.Dock="Top" Name="MyTextBox" AcceptsReturn="True" PreviewMouseDoubleClick="TextBoxSelectAll"/>

Then you set the TextBox.SelectedText Property of the TextBox to the text in the TextBox.

private void TextBoxSelectAll(object sender, MouseButtonEventArgs e) {
    // Set the event as handled
    e.Handled = true;
    // Select the Text
    (sender as TextBox).SelectAll();
}
like image 6
Bob. Avatar answered Nov 13 '22 22:11

Bob.