将焦点设置在wpf中UserControl中的文本框控件上

Pal*_*ria 14 wpf

我创建了UserControl一个在WPF中的视图(窗口)中加载的.在我的用户控件中,我放了一个TextBox.当我的视图加载时,我无法将焦点设置在此文本框上.我试过以下但没有什么对我有用:

  1. FocusManager.FocusedElement="{Binding ElementName=PwdBox}"

  2. 我创建了一个FocusExtension专注于控制的东西.

请帮忙.

Any*_*ope 15

这与Sheridan的答案类似,但不需要首先将焦点设置为控件.它会在控件可见时立即触发,并且基于父网格而不是文本框本身.

在"资源"部分:

    <Style x:Key="FocusTextBox" TargetType="Grid">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=textBoxName, Path=IsVisible}" Value="True">
                <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=textBoxName}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
Run Code Online (Sandbox Code Playgroud)

在我的网格定义中:

<Grid Style="{StaticResource FocusTextBox}" />
Run Code Online (Sandbox Code Playgroud)


She*_*dan 14

您拥有的另一个选项是bool IsFocused在视图模型中创建属性.然后,您可以添加a DataTrigger以在此属性为时设置焦点true:

在一Resources节中:

<Style x:Key="SelectedTextBoxStyle" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsFocused}" Value="True">
            <Setter Property="FocusManager.FocusedElement" 
                Value="{Binding RelativeSource={RelativeSource Self}}" />
        </DataTrigger>
    </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)

...

<TextBox Style="{StaticResource SelectedTextBoxStyle}" ... />
Run Code Online (Sandbox Code Playgroud)

请注意,有时您可能需要先将其设置为false以使其聚焦(仅当它已经存在时true):

IsFocused = false;
IsFocused = true;
Run Code Online (Sandbox Code Playgroud)


Jeh*_*hof 6

注册UserControl 的Loaded-Event并在加载 UserControl 时调用Focus()将焦点设置在 PwdBox 上。

public class MyUserControl : UserControl{

  public MyUserControl(){
    this.Loaded += Loaded;
  }

  public void Loaded(object sender, RoutedEventArgs e){
    PwdBox.Focus();
    // or FocusManager.FocusedElement = PwdBox;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Palak.Maheria 我认为加载 UserControl 时没有其他方法可以聚焦元素。使用 pur XAML 无法解决您的问题,并且在这种情况下使用 ViewModel 也不是最佳选择,因为这是视图逻辑,与视图模型无关 (2认同)