WPF:获取下一个/上一个可视对象

时间:2011-01-12 09:27:48

标签: c# wpf

我的StackPanel包含多个TextBox。有没有办法获得Next / Previous视觉元素?

我想要的功能非常类似于获取下一个对象的jQuery的.next()函数。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法来枚举Visual Tree。

public static IEnumerable<T> FindVisualChildren<T>
(DependencyObject depObj, string childName) where T : DependencyObject
{

    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {

            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            var frameworkElement = child as FrameworkElement;
            if (child != null && frameworkElement.Name == childName)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child, childName))
            {
                yield return childOfChild;
            }
        }
     }
}

假设您将textBoxes "tbInsideStackPanel"命名为,请使用它:

foreach (var textBox in FindVisualChildren<TextBox>(this.stackPanel1, 
              "tbInsideStackPanel").ToList())
{
   textBox.Background = Brushes.Blue;
}