,可以通过以下步骤实现:
下面是具体的代码示例:
private void ListBoxItem_Click(object sender, RoutedEventArgs e)
{
ListBoxItem clickedItem = sender as ListBoxItem;
if (clickedItem != null)
{
UserControl itemContent = clickedItem.Content as UserControl;
if (itemContent != null)
{
TextBox textBox = FindVisualChild<TextBox>(itemContent);
if (textBox != null)
{
textBox.Focus();
}
}
}
}
private T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child != null && child is T)
{
return (T)child;
}
else
{
T childItem = FindVisualChild<T>(child);
if (childItem != null)
return childItem;
}
}
return null;
}
这样,当用户单击ListBox中的任何ListBoxItem时,对应的UserControl中的TextBox将会获得焦点。
参考链接:
领取专属 10元无门槛券
手把手带您无忧上云