可视树代码
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
selectionChanged code
private void mylistBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (mylistBox.SelectedItem == null)
return;
foreach (Button tb in FindVisualChildren<Button>(mainListBox))
{
Debug.WriteLine(tb.Name);
}
}
输出 请注意,它会将两个按钮的名称写入两次,因此它会循环4次,并且只有2个按钮。 optionBtn optionBtn2 optionBtn optionBtn2
答案 0 :(得分:1)
mainListBox
在运行时有多少项?它必须是2,这就是它打印按钮名称两次的原因(列表框中每个项目的2次)。 SelectionChanged
或VisualTreeHelper