2012-05-23 36 views
3

我試圖找到一個回答這個問題,在每一個崗位,我覺得有一個答案遞歸地尋找孩子,但他們沒有采用隱藏式或摺疊兒童查找邏輯子包括隱藏和摺疊節點

此外,在工作每個帖子有人問這是否可能,但沒有人回答,所以我開始認爲這是不可能的

如果任何人有辦法做到這一點,我將永遠感激。

我的功能看起來是這樣的:

 public static DependencyObject FindLogicalDescendentByName(this DependencyObject source, string name) 
    { 
     DependencyObject result = null; 
     IEnumerable children = LogicalTreeHelper.GetChildren(source); 

     foreach (var child in children) 
     { 
      if (child is DependencyObject) 
      { 
       if (child is FrameworkElement) 
       { 
        if ((child as FrameworkElement).Name.Equals(name)) 
         result = (DependencyObject)child; 
        else 
         result = (child as DependencyObject).FindLogicalDescendentByName(name); 
       } 
       else 
       { 
        result = (child as DependencyObject).FindLogicalDescendentByName(name); 
       } 
       if (result != null) 
        return result; 
      } 
     } 
     return result; 
    } 

-EDITED 所以, 我意識到我的問題是,我試圖找到該項目被創建之前,

我被綁定到xaml中的屬性將會消失,並按給定名稱找到一個項目,但該項目並未在該時間點創建,如果我在xaml中重新命令了該項目,它可以工作並找到該項目...... doh!

回答

2

這裏是我的代碼,如果你指定X它的工作原理:名稱和類型的呼叫

例子:

System.Windows.Controls.Image myImage = FindChild<System.Windows.Controls.Image>(this (or parent), "ImageName"); 



/// <summary> 
/// Find specific child (name and type) from parent 
/// </summary> 
public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject 
{ 
    // Confirm parent and childName are valid. 
    if (parent == null) return null; 

    T foundChild = null; 

    int childrenCount = VisualTreeHelper.GetChildrenCount(parent); 
    for (int i = 0; i < childrenCount; i++) 
    { 
     var child = VisualTreeHelper.GetChild(parent, i); 
     // If the child is not of the request child type child 
     T childType = child as T; 
     if (childType == null) 
     { 
     // recursively drill down the tree 
     foundChild = FindChild<T>(child, childName); 

     // If the child is found, break so we do not overwrite the found child. 
     if (foundChild != null) break; 
     } 
     else if (!string.IsNullOrEmpty(childName)) 
     { 
     var frameworkElement = child as FrameworkElement; 
     // If the child's name is set for search 
     if (frameworkElement != null && frameworkElement.Name == childName) 
     { 
      // if the child's name is of the request name 
      foundChild = (T)child; 
      break; 
     } 
     } 
     else 
     { 
     // child element found. 
     foundChild = (T)child; 
     break; 
     } 
    } 

    return foundChild; 
    } 
+0

這似乎仍然沒有工作,我有2個可能的扳手拋出。1.我的控件位於第三方面板中,該面板似乎沒有任何可視樹元素,但具有邏輯樹元素,因此使用邏輯樹。 2.第三方面板和所有內部控件都在資源字典中,並用作模板。 – Kezza

+0

所以我在我想要找到的兩個控件周圍添加了一個小堆棧面板,並且我已經逐步完成了代碼,當我到達堆棧面板並從VisualTreeHelper返回childrenCount時,它的值爲1,這是控件這是可見的,不可見的控件仍然丟失......它們屬於同一類型並且都具有x:Name屬性集 – Kezza

+1

我想出了我做錯了什麼。感謝您的回覆,雖然 – Kezza