foreach 语句不能对“System.Windows.Controls.GroupBox”类型的变量进行操作
foreach 语句不能对类型的变量进行操作 'System.Windows.Controls.GroupBox' 因为 “System.Windows.Controls.GroupBox”不包含公共 “GetEnumerator”的定义
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;
}
}
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)
{
(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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第一个代码段甚至无法编译(假设
groupBox1
确实是GroupBox
),因为GroupBox
没有Children
财产。GroupBox
只能包含一个子项,由其Content
属性表示。如果您需要迭代
GroupBox
的所有可视子级,则可以使用VisualTreeHelper
类。像这样的东西:更新
好吧,你是说这不起作用,我想我明白为什么。
VisualTreeHelper
只会查找GroupBox
的第一级可视子级,它(在实现控件时)是一个Grid
。这对您没有好处,因为您需要递归到控件的子级并找到所有文本框。
在这种情况下,您最好使用网络上众多递归“FindChildren”实现之一。这是我的一个:
你可以像这样使用它:
Your first snippet won't even compile (assuming
groupBox1
is indeed aGroupBox
), sinceGroupBox
has noChildren
property.A
GroupBox
can only contain one child, represented by itsContent
property.If you need to iterate over all the visual children of a
GroupBox
, you might be able to use theVisualTreeHelper
class. Something like this: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 theGroupBox
, which (as the control is implemented) is aGrid
.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:
You can use that like this: