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!
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With