Can't set focus to a child of UserControl

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

    After having a 'WPF Initial Focus Nightmare' and based on some answers on stack, the following proved for me to be the best solution.

    First, add your App.xaml OnStartup() the followings:

    EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent,
              new RoutedEventHandler(WindowLoaded));
    

    Then add the 'WindowLoaded' event also in App.xaml :

    void WindowLoaded(object sender, RoutedEventArgs e)
        {
            var window = e.Source as Window;
            System.Threading.Thread.Sleep(100);
            window.Dispatcher.Invoke(
            new Action(() =>
            {
                window.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
    
            }));
        }
    

    The threading issue must be use as WPF initial focus mostly fails due to some framework race conditions.

    I found the following solution best as it is used globally for the whole app.

    Hope it helps...

    Oran

    0 讨论(0)
  • 2020-12-04 22:38

    After trying combinations of the suggestions above, I was able to reliably assign focus to a desired text box on a child UserControl with the following. Basically, give focus to the child control and have the child UserControl give focus to its TextBox. The TextBox's focus statement returned true by itself, however did not yield the desired result until the UserControl was given focus as well. I should also note that the UserControl was unable to request focus for itself and had to be given by the Window.

    For brevity I left out registering the Loaded events on the Window and UserControl.

    Window

    private void OnWindowLoaded(object sender, RoutedEventArgs e)
    {
        ControlXYZ.Focus();
    }
    

    UserControl

    private void OnControlLoaded(object sender, RoutedEventArgs e)
    {
        TextBoxXYZ.Focus();
    }
    
    0 讨论(0)
  • 2020-12-04 22:40

    I recently fixed this problem for a login splash screen that is being displayed via a storyboard when the main window is first loaded.

    I believe there were two keys to the fix. One was to make the containing element a focus scope. The other was to handle the Storyboard Completed event for the storyboard that was triggered by the window being loaded.

    This storyboard makes the username and password canvas visible and then fades into being 100% opaque. The key is that the username control was not visible until the storyboard ran and therefore that control could not get keyboard focus until it was visible. What threw me off for awhile was that it had "focus" (i.e. focus was true, but as it turns out this was only logical focus) and I did not know that WPF had the concept of both logical and keyboard focus until reading Kent Boogaart's answer and looking at Microsoft's WPF link text

    Once I did that the solution for my particular problem was straightforward:

    1) Make the containing element a focus scope

    <Canvas FocusManager.IsFocusScope="True" Visibility="Collapsed">
        <TextBox x:Name="m_uxUsername" AcceptsTab="False" AcceptsReturn="False">
        </TextBox>
    </Canvas>
    

    2) Attach a Completed Event Handler to the Storyboard

        <Storyboard x:Key="Splash Screen" Completed="UserNamePassword_Storyboard_Completed">
    ...
    </Storyboard>
    

    and

    3) Set my username TextBox to have the keyboard focus in the storyboard completed event handler.

    void UserNamePassword_Storyboard_Completed(object sender, EventArgs e)
    {
     m_uxUsername.Focus();
    }
    

    Note that calling item.Focus() results in the call Keyboard.Focus(this), so you don't need to call this explicitly. See this question about the difference between Keyboard.Focus(item) and item.Focus.

    0 讨论(0)
  • 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();
                    }));
                });
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 22:43

    Just recently I had a list-box that housed some TextBlocks. I wanted to be able to double click on the text block and have it turn into a TextBox, then focus on it and select all the text so the user could just start typing the new name (Akin to Adobe Layers)

    Anyway, I was doing this with an event and it just wasn't working. The magic bullet for me here was making sure that I set the event to handled. I figure it was setting focus, but as soon as the event went down the path it was switching the logical focus.

    The moral of the story is, make sure you're marking the event as handled, that might be your issue.

    0 讨论(0)
  • 2020-12-04 22:45

    I set it in the PageLoaded() or control loaded, but then I'm calling WCF async service and doing stuff that seems to lose the focus. I have to to set it at the end of all the stuff I do. That's fine and all, but sometimes I make changes to the code and then I forget that I'm also setting the cursor.

    0 讨论(0)
提交回复
热议问题