【问题标题】:Unable to make TextBox in userControl auto focus无法使 userControl 中的 TextBox 自动对焦
【发布时间】:2020-08-08 10:20:02
【问题描述】:

我正在使用用户控件中的文本框,它将在主窗口中显示为弹出窗口。现在的问题是当弹出窗口打开时,文本框应该自动聚焦。

我尝试使用 control.Focus() 和 FocusManager.FocusedElement="{Binding ElementName=TextBoxName}" 但没有用。显示光标的弹出窗口,但在我手动聚焦之前,字符不会进入其中。

<TextBlock FontSize="16" Margin="5,0,0,3" VerticalAlignment="Center" HorizontalAlignment="Left" Text="e.g. Name" 
                                   Visibility="{Binding ElementName=TextBoxName, Path=Text.IsEmpty, Converter={StaticResource BooleanToVisibilityConverter}}"/>
                        <TextBox x:Name="TextBoxName" 
                                 Text="{Binding Name}"
                                 BorderThickness="0" 
                                 Foreground="Black" 
                                 FocusManager.FocusedElement="{Binding ElementName=TextBoxName}" 
                                 MaxLength="100" 
                                 FontSize="16" 
                                 Margin="3,1,1,1"  
                                 BorderBrush="Transparent"
                                 VerticalContentAlignment="Center" 
                                 HorizontalContentAlignment="Left" 
                                 TextChanged="TextBoxName_OnTextChanged"
                                 Height="35">
                            <TextBox.InputBindings>
                                <KeyBinding Key="Enter" Command="{Binding CreateCommand}"/>
                            </TextBox.InputBindings>
                        </TextBox>

有人可以帮忙吗?

【问题讨论】:

    标签: wpf textbox autofocus


    【解决方案1】:

    可能有一个更优雅的方法,但我曾经用一个简短的代码来做到这一点。

    我为 TextBox 的 Loaded 事件添加了一个事件处理程序:

    在 XAML 中:

    <TextBox... Loaded="TextBox_Loaded">
    

    后面的代码:

    private void TextBox_Loaded(object sender, RoutedEventArgs e)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate ()
        {
             Keyboard.Focus(TextBoxName);
        }));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2022-07-22
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多