0

可视化树代码

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

4

1 回答 1

1

运行时有多少项mainListBox?它必须是 2,这就是为什么它打印按钮名称两次(列表框中的每个项目 2 次)。SelectionChangedVisualTreeHelper没有什么问题

于 2013-05-18T02:04:57.640 回答