开发者

textBox embedded in a ListBox initial focus

开发者_开发问答I want to set the focus to the first ListBox item that is a textbox. I want to be able to write in it immedatelly without the necesity to click it or press any key. I try this but doesn't work:

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

    }


it's stupid but it works only if you wait a moment, try this version:

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();
                            }
                            ));
                }
                );
        }
    }
}

I was testing locally and could not fix it until I found this question and fuzquat answer in there so vote me here and him there :D

Can't set focus to a child of UserControl


In case any body else has this issue. An UIElement has to be fully loaded before you can focus it. therefor this can be made very simple:

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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜