KeyboardFriendly
KeyboardFriendly

Reputation: 1798

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

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!

Upvotes: 6

Views: 7466

Answers (2)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

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.

Upvotes: 13

Bob.
Bob.

Reputation: 4002

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();
}

Upvotes: 7

Related Questions