我想清除网格中的所有值而不是wpf中的(datagrid)子节点

时间:2011-03-29 14:29:38

标签: c# wpf

我想清除网格子例子中的所有值,如果我的一个网格子项是文本框我想要重置它或清除网格名称而不是文本框?怎么样?不清除网格但清除文本框中的文本

2 个答案:

答案 0 :(得分:3)

以下代码应清除所有TextBox:

var textboxes = grid.Children.OfType<TextBox>();
foreach (var textBox in textboxes)
    textBox.Text = String.Empty;

答案 1 :(得分:0)

下一个函数将搜索指定对象中指定类型的所有控件:

/// <summary>
/// Helper function for searching all controls of the specified type.
/// </summary>
/// <typeparam name="T">Type of control.</typeparam>
/// <param name="depObj">Where to look for controls.</param>
/// <returns>Enumerable list of controls.</returns>
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj)
    where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

感谢此函数的作者...不记得我把它带到了哪里。

现在您可以清除所有文本框的值:

foreach (TextBox child in FindVisualChildren<TextBox>(yourGrid))
{
    child.Text = string.Empty;
}
相关问题