pri*_*kar 97 .net c# wpf textbox focus
如何将焦点设置TextBox在WPF中的元素上
我有这个代码:
txtCompanyID.Focusable = true;
txtCompanyID.Focus();
Run Code Online (Sandbox Code Playgroud)
......但它不起作用.
任何的想法?
use*_*Bee 137
在XAML中:
<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
<TextBox Name="Box" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
Ars*_*yan 49
尝试FocusManager.SetFocusedElement
FocusManager.SetFocusedElement(parentElement, txtCompanyID)
Run Code Online (Sandbox Code Playgroud)
Pet*_*ber 49
到目前为止,没有人解释为什么问题中的代码不起作用.我的猜测是代码放在Window的构造函数中.但此时设定焦点还为时过早.一旦Window准备好进行交互,就必须完成它.代码的最佳位置是Loaded事件:
public KonsoleWindow() {
public TestWindow() {
InitializeComponent();
Loaded += TestWindow_Loaded;
}
private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
txtCompanyID.Focus();
}
}
Run Code Online (Sandbox Code Playgroud)
Sve*_*lov 23
txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);
Run Code Online (Sandbox Code Playgroud)
MSDN:
整个桌面上只有一个元素具有键盘焦点.在WPF中,具有键盘焦点的元素将IsKeyboardFocused设置为true.
您可以在设置行后中断并检查IsKeyboardFocused属性的值.还要检查你是否真的到达那一行,或者你可以设置一些其他元素来获得焦点.
Any*_*ope 13
这对我来说都不起作用,因为我使用的是网格而不是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>
Run Code Online (Sandbox Code Playgroud)
在我的网格定义中:
<Grid Style="{StaticResource FocusTextBox}" />
Run Code Online (Sandbox Code Playgroud)
如果您还没有在其他答案中找到解决方案,那么我就是这样解决问题的。
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
TEXTBOX_OBJECT.Focus();
}), System.Windows.Threading.DispatcherPriority.Render);
Run Code Online (Sandbox Code Playgroud)
据我了解,其他解决方案可能不起作用,因为Focus()在应用程序呈现其他组件之前调用了 。