2011-08-01 27 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; 
      } 
     } 

但爲什麼是面向網格正確的代碼?

foreach (var txt in this.MyGrid.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

你的第一個片段甚至不會編譯(假設groupBox1確實是GroupBox),因爲GroupBox沒有Children屬性。

A GroupBox只能包含一個子項,由其Content屬性表示。

如果您需要遍歷GroupBox的所有可視子項,則可以使用VisualTreeHelper類。事情是這樣的:

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

更新

好吧,你說這是行不通的,我想我明白這是爲什麼。

VisualTreeHelper只能找到GroupBox的一級可視子項,該子項(作爲控制實施)是Grid

這對你並不好,因爲你需要遞歸到控件的子元素中並找到所有的TextBox。

在這種情況下,您最好使用圍繞Web的許多recursve「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

不起作用:的for(int i = 0; I mrJack

+1

@mrJack「不行」如何? –

+0

更新您的代碼後很漂亮。 – mrJack