Visual Tree Helper使列表框SelectionChanged激发两次

本文关键字:两次 SelectionChanged Helper Tree 列表 Visual | 更新日期: 2023-09-27 18:14:16

可视化树代码

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次,只有两个按钮。选项Btn选项Btn2选项BtnoptionBtn2

Visual Tree Helper使列表框SelectionChanged激发两次

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