可视化树代码
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;
}
}
}
}
选择更改代码
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