Select XAML TextBox in StackPanel using TextBox

2019-09-13 16:39发布

问题:

I have the following code:

//All elements edited below have already been defined in MainPage.xaml    

int index = Window_1_Document_Page_1.Children.IndexOf(sender as TextBox);
//Window_1_Document_Page_1.Focus(FocusState.Programmatic);

Window_1_Document_Page_1.Children.Remove(sender as TextBox);

Before deleting sender as TextBox, how do I set the focus to the TextBox above it?

Thanks in advance.

回答1:

Maybe there is a more elegant solution, but this should work:

        //Get index of control you want to delete
        int index = Panel.Children.IndexOf(sender as TextBox);

        //find textbox with lower index
        var control = Panel.Children.LastOrDefault(c => c is TextBox && Panel.Children.IndexOf(c) < index);
        //check if a control was found
        if (control != null)
        {
            //set focus
            var textbox = control as TextBox;
            textbox.Focus(FocusState.Programmatic);
        }

        Panel.Children.Remove(sender as TextBox);