我想将焦点设置到第一个列表框项目(文本框)。我希望能够立即写入内容,而无需单击它或按任何键。我尝试了这个但不起作用:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
listBox1.Items.Add(new TextBox() { });
(listBox1.Items[0] as TextBox).Focus();
}
最佳答案
这很愚蠢,但只有稍等片刻它才有效,试试这个版本:
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var textBox = new TextBox() {};
listBox1.Items.Add(textBox);
System.Threading.ThreadPool.QueueUserWorkItem(
(a) =>
{
System.Threading.Thread.Sleep(100);
textBox.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
textBox.Focus();
}
));
}
);
}
}
}
我正在本地测试,直到我发现这个问题和 fuzquat 答案才修复它,所以在这里投票给我,在那里投票给他:D
关于c# - 嵌入列表框初始焦点的文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7520945/