2

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

    }
mjsr
  • 7,410
  • 18
  • 57
  • 83

2 Answers2

4

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

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • 2
    WTF it works! XD...maybe in a future i'm going to try to understand it, right know I'm going to use it, thanks – mjsr Sep 22 '11 at 20:41
0

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();
}
Nawed Nabi Zada
  • 2,819
  • 5
  • 29
  • 40