将焦点设置在 wpf 中 UserControl 中的文本框控件上 [英] Set focus on a textbox control in UserControl in wpf

查看:47
本文介绍了将焦点设置在 wpf 中 UserControl 中的文本框控件上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created an UserControl which 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:

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

我创建了一个 FocusExtension 来设置焦点控制.

I have created a FocusExtension to set focus on control.

请帮忙.

推荐答案

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

Another option that you have is to create a bool IsFocusedproperty in your view model. Then you can add a DataTrigger to set the focus when this property is 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>

...

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

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

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

IsFocused = false;
IsFocused = true;

这篇关于将焦点设置在 wpf 中 UserControl 中的文本框控件上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆