c# - 嵌入列表框初始焦点的文本框

标签 c# wpf textbox listbox setfocus

我想将焦点设置到第一个列表框项目(文本框)。我希望能够立即写入内容,而无需单击它或按任何键。我尝试了这个但不起作用:

        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

Can't set focus to a child of UserControl

关于c# - 嵌入列表框初始焦点的文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7520945/

相关文章:

c# - 如何在 WCF 基于任务的操作中获取准确的异常堆栈

c# - IEnumerable 与 IQueryable 对象 - LinQ to SQL

c# - WPF中如何实现双向数据绑定(bind)?

c# - 如何以增量方式调整 WPF 窗口的大小?

c# - 如何在 vs2008 中更改 msi 安装程序包的图标并在为 c# 项目创建包后更改用户界面屏幕

c# - 具有继承的 EF Core Fluent API 配置

c# - 多线程任务更新 1 个进度条 - UI C# WPF

javascript - 文本框失去焦点后如何调用函数

c# - 向 TextBox 添加新的数据行

c# - 窗体/C# : Store/Retrieve (Persist) Content of TextBoxes between 2 Runs