window 初始化后聚焦 TextBox 和 select 所有文本

Focus TextBox and select all text after window initialization

当打开一个新的 window 时,我想聚焦一个特定的文本框和 select 其中的整个文本。 我在本教程的基础上进行了尝试: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();
    }
}

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

如何将 TextBox 和 select 其整个文本集中在 window 创建上?背后没有大量代码?

提前致谢!

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

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

我通过解决方法解决了问题。在 window 启动期间设置 TextBox 的初始文本时,会触发 OnTextBoxTextChanged 事件。我只是抓住它,select 文本,而不是 deatach 事件。

与您的答案 Dark Templar 相比,这样做的好处是,当我再次聚焦 TextBox 时,例如使用制表符,整个文本再次 selected。

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