2009-12-11 55 views
15

WPFでユニークなUidを持つコントロールがあります。そのUidでオブジェクトを取得するにはどうすればよいですか?WPFのUidでオブジェクトを取得

+1

ご了承ください。あなたのUIDは何ですか?どのように設定されていますか? –

+0

これはwpfやsilverlightのコントロールの依存関係プロパティです。私はこれを解決することができましたが、組み込みのメソッドが存在するかどうかは疑問でした。 – jose

答えて

11

あなたはかなりブルートフォースでそれを行う必要があります。ここでは、使用できるヘルパー拡張メソッドです:

private static UIElement FindUid(this DependencyObject parent, string uid) 
{ 
    var count = VisualTreeHelper.GetChildrenCount(parent); 
    if (count == 0) return null; 

    for (int i = 0; i < count; i++) 
    { 
     var el = VisualTreeHelper.GetChild(parent, i) as UIElement; 
     if (el == null) continue; 

     if (el.Uid == uid) return el; 

     el = el.FindUid(uid); 
     if (el != null) return el; 
    } 
    return null; 
} 

次に、あなたがこのようにそれを呼び出すことができます。

var el = FindUid("someUid"); 
+0

'GetChild(parent、N)'はO(N)の複雑さを持っていませんか? foreachのアプローチは私にとってはより清潔で(そしてより明確に)見えます。 – AgentFire

2

これは良いです。

public static UIElement FindUid(this DependencyObject parent, string uid) { 
    int count = VisualTreeHelper.GetChildrenCount(parent); 

    for (int i = 0; i < count; i++) { 
     UIElement el = VisualTreeHelper.GetChild(parent, i) as UIElement; 
     if (el != null) { 
      if (el.Uid == uid) { return el; } 
      el = el.FindUid(uid); 
     } 
    } 
     return null; 
} 
+0

あなたのコードがうまくいかない場合は、それを改善することはできません。あなたの再帰は壊れています。 'el.FindUid(uid)'の結果(nullでない場合)を返す必要があります。 –

2
public static UIElement GetByUid(DependencyObject rootElement, string uid) 
{ 
    foreach (UIElement element in LogicalTreeHelper.GetChildren(rootElement).OfType<UIElement>()) 
    { 
     if (element.Uid == uid) 
      return element; 
     UIElement resultChildren = GetByUid(element, uid); 
     if (resultChildren != null) 
      return resultChildren; 
    } 
    return null; 
} 
1

私はトップの答えを持っていた問題は、それが彼らのコンテンツ内の要素のために(たとえば、ユーザーコントロールなど)コンテンツコントロールの内部で見ていないということです。これらを検索するために、互換性のあるコントロールのContentプロパティを調べる関数を拡張しました。

public static UIElement FindUid(this DependencyObject parent, string uid) 
{ 
    var count = VisualTreeHelper.GetChildrenCount(parent); 

    for (int i = 0; i < count; i++) 
    { 
     var el = VisualTreeHelper.GetChild(parent, i) as UIElement; 
     if (el == null) continue; 

     if (el.Uid == uid) return el; 

     el = el.FindUid(uid); 
     if (el != null) return el; 
    } 

    if (parent is ContentControl) 
    { 
     UIElement content = (parent as ContentControl).Content as UIElement; 
     if (content != null) 
     { 
      if (content.Uid == uid) return content; 

      var el = content.FindUid(uid); 
      if (el != null) return el; 
     } 
    } 
    return null; 
} 
関連する問題