我创建了UserControl一个在WPF中的视图(窗口)中加载的.在我的用户控件中,我放了一个TextBox.当我的视图加载时,我无法将焦点设置在此文本框上.我试过以下但没有什么对我有用:
FocusManager.FocusedElement="{Binding ElementName=PwdBox}"
我创建了一个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)
注册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)
| 归档时间: |
|
| 查看次数: |
35839 次 |
| 最近记录: |