Can't set focus to a child of UserControl

后端 未结 18 585
耶瑟儿~
耶瑟儿~ 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:26

    Its stupid but it works:

    Pop a thread that waits a while then comes back and sets the focus you want. It even works within the context of an element host.

    private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    
     System.Threading.ThreadPool.QueueUserWorkItem(
                       (a) =>
                            {
                                System.Threading.Thread.Sleep(100);
                                someUiElementThatWantsFocus.Dispatcher.Invoke(
                                new Action(() =>
                                {
                                    someUiElementThatWantsFocus.Focus();
    
                                }));
                            }
                       );
    
    }
    

提交回复
热议问题