Selecting all contents of TextBox on clicking it

2019-08-09 01:51发布

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

标签: c# wpf textbox
2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-09 02:37

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();
    }
}
查看更多
老娘就宠你
3楼-- · 2019-08-09 02:56

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"
查看更多
登录 后发表回答