Silverlight和Visual Tree Manipulation

Eig*_*ite 4 silverlight dom-manipulation visual-tree

现在这可能比它的价值更麻烦但是,它现在对我来说真的很有用.

我想知道的是我如何在运行时操作Silverlight可视化树.做一些简单的事情,比如添加和删除控件都很容易,但是当你开始以任何合理的复杂度遍历树时,我发现自己渴望使用JQuery样式语法(我认为LINQ也很酷)来处理DOM节点替换,动作等.

所以我想问题是,是否有任何图书馆可以使这项工作变得更容易,或者是否有一些我错过的东西?

Ant*_*nes 6

是的Linq扩展方法是您所追求的,但您需要首先放置一个小型基础设施: -

public static class VisualTreeEnumeration
{
    public static IEnumerable<DependencyObject> Descendents(this DependencyObject root, int depth)
    {
        int count = VisualTreeHelper.GetChildrenCount(root);
        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(root, i);
            yield return child;
            if (depth > 0)
            {
                foreach (var descendent in Descendents(child, --depth))
                    yield return descendent;
            }
        }
     }

     public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
     {
          return Descendents(root, Int32.MaxValue); 
     }

     public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)
     {
          DependencyObject current = VisualTreeHelper.GetParent(root);
          while (current != null)
          {
              yield return current;
              current = VisualTreeHelper.GetParent(current);
          }
     }
 }
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用Linq使用Linq查询可视化树.一些例子:-

 // Get all text boxes in usercontrol:-
 this.Descendents().OfType<TextBox>();

 // All UIElement direct children of the layout root grid:-
 LayoutRoot.Descendents(0).OfType<UIElement>();

 // Find the containing `ListBoxItem` for an element:-
 elem.Ancestors().OfType<ListBoxItem>.FirstOrDefault();

 // Seek button with name "PinkElephants" even if outside of the current Namescope:-
 this.Descendents()
    .OfType<Button>()
    .FirstOrDefault(b => b.Name == "PinkElephants");
Run Code Online (Sandbox Code Playgroud)