using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;

namespace SilverlightApplication36
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            testGrid.ItemsSource = HierarchicalItem.GenerateHierarchy(3);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DeepClear(testGrid);
        }

        private static void DeepClear(RadGridView grid)
        {
            grid.Columns.Clear();
            IEnumerable<GridViewRow> rows = grid.ChildrenOfType<GridViewRow>().Where(s => s.Item != null);
            foreach (GridViewRow row in rows)
            {
                if (row.ChildrenOfType<RadGridView>().Count > 0)
                {
                    DeepClear(row.ChildrenOfType<RadGridView>().First());
                }
            }
        }
    }

    public class HierarchicalItem
    {
        public string Label { get; set; }
        public ObservableCollection<HierarchicalItem> Children { get; set; }

        public HierarchicalItem(int id)
        {
            Label = string.Format("Item{0}", id);
            Children = new ObservableCollection<HierarchicalItem>();
        }

        public static ObservableCollection<HierarchicalItem> GenerateHierarchy(int count)
        {
            Random rnd = new Random();
            ObservableCollection<HierarchicalItem> res = new ObservableCollection<HierarchicalItem>();

            for (int i = 0; i < count; i++)
            {
                res.Add(new HierarchicalItem(rnd.Next(100)));
                for (int j = 0; j < count; j++)
                {
                    res[i].Children.Add(new HierarchicalItem(rnd.Next(100)));
                }
            }
            return res;
        }
    }
}
