I have one TextBox. On clicking it, all the contents of the TextBox should be selected. What is the solution for this?
The code I have tried is:
<TextBox Name="questionTitle_textBox" Text="Question title" PreviewMouseDown="questionTitle_textBox_PreviewMouseDown"/>
The function questionTitle_textBox_PreviewMouseDown
is defined as
private void questionTitle_textBox_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
questionTitle_textBox.SelectAll();
}
This works
<TextBox Name="questionTitle_textBox" Text="Question title" GotFocus="questionTitle_textBox_GotFocus" PreviewMouseLeftButtonDown="questionTitle_textBox_PreviewMouseLeftButtonDown"/>
and in code behind
private void questionTitle_textBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
TextBox tb = (sender as TextBox);
if (tb != null)
{
if (!tb.IsFocused)
{
e.Handled = true;
tb.Focus();
}
}
}
private void questionTitle_textBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = (sender as TextBox);
if (tb != null)
{
tb.SelectAll();
}
}
You can try to add a trigger to your TextBox
<TextBox Name="questionTitle_textBox" Text="Question title" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<local:SelectAllAction />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
Add SelectAllAction.cs
to your project:
namespace YourNameSpace
{
public class SelectAllAction : TriggerAction<TextBox>
{
protected override void Invoke(object parameter)
{
if(this.AssociatedObject != null)
{
this.AssociatedObject.SelectAll();
}
}
}
}
You also need to add two namepsaces to your XAML to use the trigger. The name of my project was WpfApplication1, so you will probably need to change that:
xmlns:local ="clr-namespace:YourNameSpace"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"