2012-04-23 14 views
29

ComboBoxの子コントロールをWPFのMyContainerGridにどのようにして取得できますか?WPFコンテナの子をどのようにタイプで取得するのですか?

<Grid x:Name="MyContainer">      
    <Label Content="Name" Name="label1" /> 
    <Label Content="State" Name="label2" /> 
    <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox1"/> 
    <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox3" /> 
    <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox4" /> 
</Grid> 

この行は私にエラーを与える:

var myCombobox = this.MyContainer.Children.GetType(ComboBox); 

答えて

63

この拡張メソッドは、の子要素のために再帰的に検索します希望のタイプ:

public static T GetChildOfType<T>(this DependencyObject depObj) 
    where T : DependencyObject 
{ 
    if (depObj == null) return null; 

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
    { 
     var child = VisualTreeHelper.GetChild(depObj, i); 

     var result = (child as T) ?? GetChildOfType<T>(child); 
     if (result != null) return result; 
    } 
    return null; 
} 

これを使用すると、MyContainer.GetChildOfType<ComboBox>()を求めることができます。 (画面の)所定の点を含んでいる特定のタイプの最初の子のための

+7

' LogicalTreeHelper.FindLogicalNode(DependencyObject depObj、string elementName) 'で検索しません。同じ目的を達成するために働いています。 – Paul

+0

これを使用してくださいhttp://stackoverflow.com/a/978352/690656 – Andreas

32

子供のUIElementのコレクションです。したがって、アイテムを繰り返し処理し、各アイテムに対して必要なタイプかどうかを判断する必要があります。

var comboBoxes = this.MyContainer.Children.OfType<ComboBox>(); 

この方法は、あなたのケースでは、唯一の要素をその種類とリターンに基づいてコレクションをフィルタリングします。幸いにも、あなたが便利Extension Method構文を使用して呼び出すことができる、まさにこの、すなわちEnumerable.OfType<T>のためのLINQの方法は、すでにそこにありますタイプComboBoxです。

あなたが最初のコンボボックスを(あなたの変数名が示唆するように)したい場合は、あなただけのクエリにFirstOrDefault()への呼び出しを追加することができます

var myComboBox = this.MyContainer.Children.OfType<ComboBox>().FirstOrDefault(); 
+0

はうまくいきます。ありがとう – ArchieTiger

+1

これは 'ContentControl –

2

検索:

(パラメータ「ポイント」ビジュアルタイプで宣言された「PointToScreen」関数()の呼び出しの結果です)
private TDescendantType FindDescendant<TDescendantType>(DependencyObject parent, Point screenPoint) 
     where TDescendantType : DependencyObject 
{ 
    int count = VisualTreeHelper.GetChildrenCount(parent); 
    for (int i = 0; i < count; i++) 
    { 
     var child = VisualTreeHelper.GetChild(parent, i); 
     if (child is Visual) 
     { 
      Point point = ((Visual)child).PointFromScreen(screenPoint); 
      Rect rect = VisualTreeHelper.GetDescendantBounds((Visual)child); 

      if (!rect.Contains(point)) 
       continue; 
     } 

     if (child is TDescendantType) 
     { 
      return (TDescendantType)child; 
     } 

     child = FindDescendant<TDescendantType>(child, screenPoint); 
     if (child != null) 
     { 
      return (TDescendantType)child; 
     } 
    } 
    return null; 
} 
+0

詳細については、[編集]をクリックしてください。検索可能なコンテンツが含まれていないため、コード専用と「試してください」という回答は(推奨されません)(// meta.stackexchange.com/questions/196187)、誰かが「これを試してみる」理由を説明していません。私たちはここで知識のためのリソースとなるよう努力しています。 – Mogsdad

関連する問題