Select XAML StackPanel 中的 TextBox 使用 TextBox 的索引

Select XAML TextBox in StackPanel using TextBox's Index

我有以下代码:

//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);

在删除sender as TextBox之前,如何将焦点设置到它上面的TextBox?

提前致谢。

也许有更优雅的解决方案,但这应该可行:

        //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);