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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19225443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:57:58  来源:igfitidea点击:

Set focus on a textbox control in UserControl in wpf

wpf

提问by Palak.Maheria

I have created an UserControlwhich is loaded in a View (Window) in WPF. In my user control I have put a TextBox. I am unable to set focus on this text box when my view loads. I have tried following but nothing works for me:

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

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

  2. I have created a FocusExtensionto set focus on control.

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

  2. 我创建了一个FocusExtension来集中控制。

Please help.

请帮忙。

采纳答案by Sheridan

Another option that you have is to create a bool IsFocusedproperty in your view model. Then you can add a DataTriggerto set the focus when this property is true:

您拥有的另一个选择是bool IsFocused在您的视图模型中创建一个属性。然后你可以添加一个DataTrigger来设置这个属性时的焦点true

In a Resourcessection:

在一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>

...

...

<TextBox Style="{StaticResource SelectedTextBoxStyle}" ... />

Note that at times, you mayneed to set it to false first to get it to focus (only when it is already true):

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

IsFocused = false;
IsFocused = true;

回答by Anya Hope

This is similar to Sheridan's answer but does not require focus to be set to the control first. It fires as soon as the control is made visible and is based on the parent grid rather than the textbox itself.

这类似于 Sheridan 的回答,但不需要先将焦点设置到控件上。一旦控件可见并且基于父网格而不是文本框本身,它就会触发。

In the 'Resources' section:

在“资源”部分:

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

In my grid definition:

在我的网格定义中:

<Grid Style="{StaticResource FocusTextBox}" />

回答by nmclean

Keyboard focus will be set when the FocusManager.FocusedElementproperty is set. Since the property is set when an element is initialized, this is often useful for setting initial focus.

设置FocusManager.FocusedElement属性时将设置键盘焦点。由于该属性是在元素初始化时设置的,因此这对于设置初始焦点通常很有用。

However this is not quite the same thing as setting focus on load. If it is unloaded and reloaded, for example, the keyboard focus will not move the second time. The actual intended purpose of the FocusedElement property is for temporary focus scopes (for example, when a menu is opened, the FocusedElement of the window is kept separate from the keyboard focus because the menu is a separate focus scope -- and keyboard focus returns to the FocusedElement when the menu is closed). If you set FocusedElement on a Window, it will not persist -- since a Window is a focus scope, it will automatically update its FocusedElement whenever you move keyboard focus within it.

然而,这与将焦点设置在负载上并不完全相同。例如,如果卸载并重新加载,则键盘焦点不会第二次移动。FocusedElement 属性的实际预期用途是用于临时焦点范围(例如,当打开菜单时,窗口的 F​​ocusedElement 与键盘焦点保持分离,因为菜单是一个单独的焦点范围——并且键盘焦点返回到菜单关闭时的 FocusedElement)。如果您在 Window 上设置 FocusedElement,它不会持续存在——因为 Window 是一个焦点范围,每当您在其中移动键盘焦点时,它都会自动更新其 FocusedElement。

To set focus on the Loadedevent (without using code-behind), this attached property should work for you:

要将焦点设置在Loaded事件上(不使用代码隐藏),此附加属性应该适合您:

public static class FocusExtensions {
    public static readonly DependencyProperty LoadedFocusedElementProperty =
        DependencyProperty.RegisterAttached("LoadedFocusedElement", typeof(IInputElement), typeof(FocusExtension),
                                            new PropertyMetadata(OnLoadedFocusedElementChanged));

    public static IInputElement GetLoadedFocusedElement(DependencyObject element) {
        return (IInputElement)element.GetValue(LoadedFocusedElementProperty);
    }

    public static void SetLoadedFocusedElement(DependencyObject element, bool value) {
        element.SetValue(LoadedFocusedElementProperty, value);
    }

    private static void OnLoadedFocusedElementChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) {
        var element = (FrameworkElement)obj;

        var oldFocusedElement = (IInputElement)e.OldValue;
        if (oldFocusedElement != null) {
            element.Loaded -= LoadedFocusedElement_Loaded;
        }

        var newFocusedElement = (IInputElement)e.NewValue;
        if (newFocusedElement != null) {
            element.Loaded += LoadedFocusedElement_Loaded;
        }
    }

    private static void LoadedFocusedElement_Loaded(object sender, RoutedEventArgs e) {
        var element = (FrameworkElement)sender;
        var focusedElement = GetLoadedFocusedElement(element);
        focusedElement.Focus();
    }
}

The usage is the same as FocusManager.FocusedElement, i.e.:

用法同FocusManager.FocusedElement,即:

local:FocusExtensions.LoadedFocusedElement="{Binding ElementName=PwdBox}"

回答by Jehof

Register the Loaded-Eventof your UserControl and set the Focus on your PwdBox by calling Focus()when your UserControl is loaded.

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

回答by Theike

What i use in my authentication manager:

我在身份验证管理器中使用的内容:

private void SelectLogicalControl()
{
    if (string.IsNullOrEmpty(TextboxUsername.Text))
        TextboxUsername.Focus();
    else
    {
        TextboxPassword.SelectAll();
        TextboxPassword.Focus();
    }
}

If no username is set, focus on the username-textbox; otherwise the (select all) passwordbox. This is in the codebehind-file, so not viewmodel ;)

如果没有设置用户名,则关注用户名文本框;否则(全选)密码框。这是在代码隐藏文件中,所以不是视图模型;)

回答by Andrew Arnott

It worked for me to simply add this attribute to the opening UserControl tag in my XAML:

我只需将此属性添加到 XAML 中的开始 UserControl 标记即可:

FocusManager.FocusedElement="{Binding ElementName=DisplayName, Mode=OneTime}"

Where DisplayName is the name of the textbox I want to receive focus.

其中 DisplayName 是我想要获得焦点的文本框的名称。

回答by Rankit

On load event set the keyboard focus :

在加载事件时设置键盘焦点:

Keyboard.Focus(control);

Keyboard.Focus(control);