2011-08-01 6 views
0

foreach文を操作することはできません 「System.Windows.Controls.GroupBoxので、タイプ の変数に「System.Windows.Controls.GroupBox」を操作することはできませんGetEnumeratorメソッド ''の公開 の定義が含まれていない'foreach文は、型の変数に「System.Windows.Controls.GroupBox」

mycode:

foreach (var txt in this.groupBox1.Children) 
     { 
      if (txt is TextBox) 
      { 
       (txt as TextBox).Text = string.Empty; 
      } 
     } 

しかし、なぜグリッドの正しいコードはありますか?

groupBoxの正しいコードは何ですか?

///////////////// 編集

正しいコード:

foreach (var txt in this.MyGridInGroupBox.Children) 
    { 
     if (txt is TextBox) 
     { 
      (txt as TextBox).Text = string.Empty; 
     } 
    } 

答えて

5

あなたの最初のスニペットでもコンパイルされませんGroupBoxにはChildrenという特性がないので、groupBox1が実際にはGroupBoxであると仮定します。

GroupBoxには、子を1人だけ含めることができ、その子はContentプロパティで表されます。

GroupBoxのすべての視覚的な子を反復処理する必要がある場合は、VisualTreeHelperクラスを使用できます。このような何か:

for (int i = 0; i < VisualTreeHelper.GetChildrenCount(groupBox1); i++) 
{ 
    var txt = VisualTreeHelper.GetChild(groupBox1, i); 
    if (txt is TextBox) ... 
} 

更新

[OK]を、あなたはこれが動作しないことを言っている、と私は理由を理解すると思います。

VisualTreeHelperは、(コントロールが実装されている)GridであるGroupBoxの第1レベルの視覚的な子のみを見つけます。

これは、あなたがコントロールの子に再帰し、すべてのTextBoxを見つける必要があるため、これはあなたにとっては良いことではありません。

この場合、Web上で多くの「FindChildren」実装を再利用する方がよいでしょう。ここでは鉱山の一つです:

public static class DependencyObjectExtensions 
{ 
    public static IEnumerable<T> GetVisualChildren<T>(this DependencyObject depObj) 
     where T : DependencyObject 
    { 
     if (depObj == null) yield break; 

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

      var t = child as T; 
      if (t != null) yield return t; 

      foreach (var item in GetVisualChildren<T>(child)) 
      { 
       yield return item; 
      } 
     } 
    } 
} 

あなたはこのようにそれを使用することができます:

foreach (var txt in groupBox1.GetVisualChildren<TextBox>()) 
{ 
    txt.Text = String.Empty; 
} 
+0

動作しません:のために(私は= 0をint型;私はVisualTreeHelper.GetChildrenCount(groupBox1を)<;私は++) { VARをtxt = VisualTreeHelper.GetChild(groupBox1、i); if(txtがTextBoxの場合) { (TextBoxとしてのtxt).Text = string.Empty; } } – mrJack

+1

@mrJack「うまくいかない」とは? –

+0

あなたのコードを更新した後は美しいです。 – mrJack

関連する問題