将焦点设置在 wpf 中 UserControl 中的文本框控件上 [英] Set focus on a textbox control in UserControl in wpf
问题描述
我创建了一个 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:
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 IsFocused
property 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屋!