如何在WPF中设置TextBox
元素的焦点。
我有这段代码:
txtCompanyID.Focusable = true;
txtCompanyID.Focus();
... 但是它没有起作用。
有什么想法吗?
在 XAML 中:
<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
<TextBox Name="Box" />
</StackPanel>
到目前为止,还没有人解释为什么问题中的代码不起作用。我猜测代码放在了Window的构造函数中。但此时设置焦点为时机过早。必须在窗口准备好交互后才能执行。最好的地方是Loaded事件中的代码:
public KonsoleWindow() {
public TestWindow() {
InitializeComponent();
Loaded += TestWindow_Loaded;
}
private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
txtCompanyID.Focus();
}
}
Focus()
需要一个焦点状态参数,例如 txtCompanyId.Focus(FocusState.Keyboard)
。 - Dan尝试使用 FocusManager.SetFocusedElement
FocusManager.SetFocusedElement(parentElement, txtCompanyID)
txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);
MSDN:
在整个桌面上,只能有一个具有键盘焦点的元素。在 WPF 中,具有键盘焦点的元素将设置 IsKeyboardFocused 为 true。
您可以在设置行之后进行分隔,并检查 IsKeyboardFocused
属性的值。还要检查是否确实到达该行或者您设置了其他元素来获取焦点。
MyTextBox.Focus ( );
因为我使用的是网格而不是StackPanel,所以这些都对我没用。
最后我找到了这个例子: http://spin.atomicobject.com/2013/03/06/xaml-wpf-textbox-focus/
并将其修改为:
在“资源”部分:
<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>
在我的网格定义中:
<Grid Style="{StaticResource FocusTextBox}" />
如果您在其他答案中没有找到解决方案,那么这就是我解决问题的方法。
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
TEXTBOX_OBJECT.Focus();
}), System.Windows.Threading.DispatcherPriority.Render);
据我所知,其他解决方案可能无法使用,因为在应用程序渲染其他组件之前调用了 Focus()
。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
txtIndex.Focusable = true;
txtIndex.Focus();
}
<TextBox Text="This control is focused on startup">
<dxmvvm:Interaction.Behaviors>
<dxmvvm:FocusBehavior/>
</dxmvvm:Interaction.Behaviors>
</TextBox>
它允许您在控件加载时、引发某个事件或更改属性时集中控制。