Here is the XAML of my list box:
I was using the VisualTreeHelper class to iterate over the ListBox, but I was not getting to the ListBoxItems. I was getting ListBox, ScrollViewer, Border, Grid, ContentPresenter, ItemsPresenter, VirtualizingStackPanel, and other controls, but no ListBoxItems. After reading this, the problem was fixed by calling the
UpdateLayoutmethod. The rest was simple. Here is my code.
void SetFocusOnTextBox(DependencyObject element, int primaryKey) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) { if (foundItem == false) //global flag that stops processing once the control is found { DependencyObject child = VisualTreeHelper.GetChild(element, i); StackPanel s = child as StackPanel; if (s != null) FindAllChildrenOfAStackPanel(child, primaryKey); if (foundItem == false) SetFocusOnTextBox(child, primaryKey); else break; } } foundItem = false; } void FindAllChildrenOfAStackPanel(DependencyObject element, int primaryKey) { StackPanel s = element as StackPanel; if (s != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) { TextBox t = VisualTreeHelper.GetChild(element, i) as TextBox; if (t != null) if (t.Name == primaryKey) { t.Focus(); foundItem = true; break; } } } }
No comments:
Post a Comment