单击选择TextBox的所有内容

时间:2015-07-08 11:49:35

标签: c# wpf textbox

我有一个TextBox。单击它时,应选择TextBox的所有内容。这是什么解决方案? 我试过的代码是:

<TextBox Name="questionTitle_textBox" Text="Question title" PreviewMouseDown="questionTitle_textBox_PreviewMouseDown"/>

函数questionTitle_textBox_PreviewMouseDown定义为

private void questionTitle_textBox_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
        questionTitle_textBox.SelectAll();
}

2 个答案:

答案 0 :(得分:2)

这有效

<TextBox Name="questionTitle_textBox" Text="Question title" GotFocus="questionTitle_textBox_GotFocus" PreviewMouseLeftButtonDown="questionTitle_textBox_PreviewMouseLeftButtonDown"/>

并在代码中

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

答案 1 :(得分:0)

您可以尝试在TextBox中添加触发器

<TextBox Name="questionTitle_textBox" Text="Question title" >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="GotFocus">
            <local:SelectAllAction />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>

SelectAllAction.cs添加到您的项目中:

namespace YourNameSpace
{
    public class SelectAllAction : TriggerAction<TextBox>
    {
        protected override void Invoke(object parameter)
        {
            if(this.AssociatedObject != null)
            {
                this.AssociatedObject.SelectAll();
            }
        }
    }
}

您还需要向XAML添加两个名称以使用触发器。我的项目名称是WpfApplication1,因此您可能需要更改它:

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