using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using Telerik.Windows.Controls;
using System.Text;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            DataContext = new MyDataContext();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var grid1Output = RadGridView1.ToExcelML();
            var grid2Output = RadGridView2.ToExcelML().Replace("Worksheet1", "Worksheet2");

            var workBook = grid1Output.Replace("</Worksheet>", "</Worksheet>" + 
                grid2Output.Substring(grid2Output.IndexOf("<Worksheet"), 
                    grid2Output.IndexOf("</Worksheet")- grid2Output.IndexOf("<Worksheet")) + "</Worksheet>");

            var dialog = new SaveFileDialog();
            dialog.DefaultExt = "xml";
            dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", "xml", "ExcelML");
            dialog.FilterIndex = 1;

            if (dialog.ShowDialog() == true)
            {
                using (var stream = dialog.OpenFile())
                {
                    Byte[] bytes = Encoding.UTF8.GetBytes(workBook);
                    stream.Write(bytes, 0, bytes.Length);
                }
            }
        }
    }

    public class MyDataContext
    {
        ObservableCollection<int> _Items1;
        public ObservableCollection<int> Items1
        {
            get
            {
                if (_Items1 == null)
                {
                    _Items1 = new ObservableCollection<int>(from i in Enumerable.Range(0, 100) select i);
                }
                return _Items1;
            }
        }

        ObservableCollection<int> _Items2;
        public ObservableCollection<int> Items2
        {
            get
            {
                if (_Items2 == null)
                {
                    _Items2 = new ObservableCollection<int>(from i in Enumerable.Range(100, 200) select i);
                }
                return _Items2;
            }
        }
    }
}
