我想将焦点设置到作为文本框的第一个 ListBox 项。我希望能够立即在其中写入,而无需单击它或按任何键。我试试这个但不起作用:
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
万一其他机构有这个问题。UIElement 必须先完全加载,然后才能聚焦它。因此,这可以非常简单:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
listBox1.Items.Add(new TextBox() { });
var txBox = listBox1.Items[0] as TextBox;
txBox.Loaded += (txbSender, args) => (txbSender as TextBox)?.Focus();
}