textBox嵌入在ListBox初始焦点中

时间:2011-09-22 20:19:22

标签: c# wpf textbox listbox setfocus

我想将焦点设置为第一个作为文本框的ListBox项。我希望能够立即写入,无需点击它或按任意键。我尝试这个但是不起作用:

        private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        listBox1.Items.Add(new TextBox() { });
        (listBox1.Items[0] as TextBox).Focus();

    }

2 个答案:

答案 0 :(得分:4)

这是愚蠢的,但只有你等一下,它才有效,试试这个版本:

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

Can't set focus to a child of UserControl

答案 1 :(得分:0)

如果其他人有此问题。必须先完全加载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();
}