Search code examples
xamluwpuser-controlsuwp-xaml

How to set focus to an element inside of user control on UWP?


I created my own UserControl, inside of it, I placed a ListView. But When I set the UserControl to show, I can't set focus to ListViewItem. The Focus is still in the original page.

For how to show my UserControl, I use Popup.

Popup popup = new Popup();
popup.Child = this;
popup.IsOpen = true;

Solution

  • Setting a Focus for a ListView takes place when the ListView has been loaded into the visual tree and ready for interaction.

    We assume that you have created a UserControl that contains a ListView, then the method for setting the Focus for the ListView should be done in the UserControl_Loaded or ListView_Loaded event.

    public PopupControl()
    {
        this.InitializeComponent();
        // Data init
        var _popup = new Popup();
        _popup.Child = this;
        _popup.IsOpen = true;
    }
    
    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        TestListView.Focus(FocusState.Keyboard);
    }
    

    Best regards.