I have the following XAML:
<ListBox HorizontalAlignment="Left" Margin="0,6,0,10" Name="listBox1" Width="468" ItemsSource="{Binding}" Grid.ColumnSpan="1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Name="txt1" Text="{Binding Propty1}" IsEnabled="False"></TextBox>
<CheckBox IsChecked="{Binding Propty2}" Name="{Binding Propty2}" Click="chk_Clicked"></CheckBox>
<TextBox Text="{Binding Propty2}" Name="{Binding Propty3}" GotFocus="txt_GotFocus" LostFocus="txt_OnLostFocus" KeyDown="txt_OnKeyDown"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
After an event happens (a button outside of listbox is clicked, then the data in the listbox is reloaded), I need to focus on one of the textboxes in the listbox. I use VisualTreeHelper to go through the listbox. Here is the code:
void SetFocusOnTextBox(DependencyObject element)
{
ListBoxItem listItem = element as ListBoxItem;
if (listItem != null)
{
//find textbox and set focus here
}
int children = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < children; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(element, i);
SetFocusOnTextBox(child);
}
}
However, I don't get any items of type listbox when I call the method in the following line of code:
SetFocusOnTextBox(listBox1);
I get ListBox, ScrollViewer, Border, Grid, ContentPresenter, ItemsPresenter, VirtualizingStackPanel and so on, but no listboxitems. What am I doing wrong? How do I find listboxitems (and then textboxes) in the listbox? Thank you.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…