foreach statement cannot operate on variables of type 'System.Windows.Controls.GroupBox'
foreach statement cannot operate on variables of type 'System.Windows.Controls.GroupBox' because 'System.Windows.Controls.GroupBox' does not contain a public definition for 'GetEnumerator'
mycode :
foreach (var txt in this.groupBox1.Children)
{
if (txt is TextBox)
{
(txt as TextBox).Text = string.Empty;
}
}
But why is the correct code for the Grid ?
foreach (var txt in this.MyGrid.Children)
{
if (txt is TextBox)开发者_JAVA技巧
{
(txt as TextBox).Text = string.Empty;
}
}
What is the correct code for groupBox?
/////////////////editing
Correct code:
foreach (var txt in this.MyGridInGroupBox.Children)
{
if (txt is TextBox)
{
(txt as TextBox).Text = string.Empty;
}
}
Your first snippet won't even compile (assuming groupBox1
is indeed a GroupBox
), since GroupBox
has no Children
property.
A GroupBox
can only contain one child, represented by its Content
property.
If you need to iterate over all the visual children of a GroupBox
, you might be able to use the VisualTreeHelper
class. Something like this:
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(groupBox1); i++)
{
var txt = VisualTreeHelper.GetChild(groupBox1, i);
if (txt is TextBox) ...
}
Update
Ok, you're saying that this doesn't work, and I think I understand why.
The VisualTreeHelper
will only find the first-level visual children of the GroupBox
, which (as the control is implemented) is a Grid
.
This is no good to you, because you need to recurse down into the children of the control and find all the TextBoxes.
In that case, you're better off using one of the many recursve "FindChildren" implementations around the web. Here's one of mine:
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;
}
}
}
}
You can use that like this:
foreach (var txt in groupBox1.GetVisualChildren<TextBox>())
{
txt.Text = String.Empty;
}
精彩评论