Can't set focus to a child of UserControl

后端 未结 18 577
耶瑟儿~
耶瑟儿~ 2020-12-04 21:55

I have a UserControl which contains a TextBox. When my main window loads I want to set the focus to this textbox so I added Focusable=\"True

18条回答
  •  既然无缘
    2020-12-04 22:42

    I converted fuzquat's answer to an extension method. I'm using this instead of Focus() where Focus() did not work.

    using System;
    using System.Threading;
    using System.Windows;
    
    namespace YourProject.Extensions
    {
        public static class UIElementExtension
        {
            public static void WaitAndFocus(this UIElement element, int ms = 100)
            {
                ThreadPool.QueueUserWorkItem(f =>
                {
                    Thread.Sleep(ms);
    
                    element.Dispatcher.Invoke(new Action(() =>
                    {
                        element.Focus();
                    }));
                });
            }
        }
    }
    

提交回复
热议问题