【问题标题】:Focus TextBox and select all text after window initialization聚焦 TextBox 并在窗口初始化后选择所有文本
【发布时间】:2016-06-23 10:11:31
【问题描述】:

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

提前致谢!

【问题讨论】:

    标签: c# wpf xaml textbox focus


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我通过解决方法解决了这个问题。在窗口启动期间设置 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;
          }
      

      【讨论】:

        猜你喜欢
        • 2014-12-27
        • 2011-11-02
        • 2010-10-30
        • 1970-01-01
        • 1970-01-01
        • 2011-05-08
        • 1970-01-01
        • 2021-04-16
        • 2020-05-01
        相关资源
        最近更新 更多