繁体   English   中英

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

[英]Focus TextBox and select all text after window initialization

当打开一个新窗口时,我要聚焦特定的文本框并在其中选择整个文本。 我在本教程的基础上进行了尝试: 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聚焦并在创建窗口时选择其整个文本? 没有大量的代码吗?

提前致谢!

很好,您可以使用“ window_loaded”事件来使文本框聚焦,这是一个示例:

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

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

与您的答案“黑暗圣堂武士”相比,这样做的好处是,当我再次使TextBox(例如,带有tab)聚焦时,将再次选择整个文本。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM