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

时间:2013-05-18 01:16:42

标签: c# windows-phone-7 windows-phone-8

可视树代码

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

1 个答案:

答案 0 :(得分:1)

mainListBox在运行时有多少项?它必须是2,这就是它打印按钮名称两次的原因(列表框中每个项目的2次)。 SelectionChanged或VisualTreeHelper

没有任何问题