mrJ*_*ack 0 wpf foreach c#-4.0
foreach语句不能对'System.Windows.Controls.GroupBox'类型的变量进行操作,因为'System.Windows.Controls.GroupBox'不包含'GetEnumerator'的公共定义
我的代码:
foreach (var txt in this.groupBox1.Children)
{
if (txt is TextBox)
{
(txt as TextBox).Text = string.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
但为什么Grid的代码正确?
foreach (var txt in this.MyGrid.Children)
{
if (txt is TextBox)
{
(txt as TextBox).Text = string.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
groupBox的正确代码是什么?
///////////////// 编辑
正确的代码:
foreach (var txt in this.MyGridInGroupBox.Children)
{
if (txt is TextBox)
{
(txt as TextBox).Text = string.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
你的第一个片段甚至不会编译(假设groupBox1
确实是一个GroupBox
),因为GroupBox
没有Children
属性.
A GroupBox
只能包含一个孩子,由其Content
属性表示.
如果你需要迭代a的所有视觉子元素GroupBox
,你可能可以使用VisualTreeHelper
该类.像这样的东西:
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(groupBox1); i++)
{
var txt = VisualTreeHelper.GetChild(groupBox1, i);
if (txt is TextBox) ...
}
Run Code Online (Sandbox Code Playgroud)
更新
好的,你说这不起作用,我想我理解为什么.
在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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以这样使用:
foreach (var txt in groupBox1.GetVisualChildren<TextBox>())
{
txt.Text = String.Empty;
}
Run Code Online (Sandbox Code Playgroud)