聚焦TextBox并在窗口初始化后选择所有文本

时间:2016-06-23 10:11:31

标签: c# wpf xaml textbox focus

当打开一个新窗口时,我想要聚焦特定的文本框并选择其中的整个文本。 我在本教程的基础上尝试了它:https://blogs.msdn.microsoft.com/argumentnullexceptionblogpost/2013/04/12/a-simple-selectall-behavior-for-textboxes/

为了聚焦元素,我在网格中使用它:

<Grid d:DataContext="{StaticResource DesignTimeLayerViewModel1}" FocusManager.FocusedElement="{Binding ElementName=LayerNameInput}"> 

并尝试了互动行为:

<TextBox x:Name="LayerNameInput"
    Text="{Binding MapLayerName, UpdateSourceTrigger=PropertyChanged}"
    VerticalContentAlignment="Center"
    Width="240">
    <i:Interaction.Behaviors>
        <behaviors:SelectAllTextBoxBehavior></behaviors:SelectAllTextBoxBehavior>
    </i:Interaction.Behaviors>
</TextBox>

行为代码:

public class SelectAllTextBoxBehavior : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.GotFocus += this.OnTextBoxGotFocus;
    }

    protected override void OnDetaching()
    {
        this.AssociatedObject.GotFocus -= this.OnTextBoxGotFocus;
        base.OnDetaching();
    }

    private void OnTextBoxGotFocus(object sender, RoutedEventArgs e)
    {
        this.AssociatedObject.SelectAll();
    }
}

问题是绑定。创建窗口时,行为触发正确,但实际上TextBox中没有文本。然后初始化TextBox并将文本设置为绑定变量的值,并且选择将丢失。 如果我通过多次使用Tab重新聚焦TextBox,它可以正常工作。

如何关注TextBox并在窗口创建时选择整个文本?没有大量的代码吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

你可以使用“window_loaded”事件来聚焦你的文本框 这是一个例子:

    private void window_Loaded(object sender, RoutedEventArgs e)
    {
        textBox.Focus();
        textBox.SelectAll();
    }

答案 1 :(得分:0)

我通过解决方法修复了问题。在窗口启动期间设置TextBox的初始文本时,将触发OnTextBoxTextChanged事件。我抓住它,选择文本,然后去除事件。

与你的回答Dark Templar相比,这个好处是,当我再次聚焦TextBox时,例如使用选项卡,再次选择整个文本。

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.GotFocus += OnTextBoxGotFocus;
        AssociatedObject.TextChanged += OnTextBoxTextChanged;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.GotFocus -= OnTextBoxGotFocus;
        AssociatedObject.TextChanged -= OnTextBoxTextChanged;
        base.OnDetaching();
    }

    private void OnTextBoxGotFocus(object sender, RoutedEventArgs e)
    {
        AssociatedObject.SelectAll();
    }

    private void OnTextBoxTextChanged(object sender, RoutedEventArgs e)
    {
        AssociatedObject.SelectAll();
        AssociatedObject.TextChanged -= OnTextBoxTextChanged;
    }
相关问题