using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Data;
using System.Collections.ObjectModel;

namespace RadGridView_EF_WPF
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();

			DataContext = new NorthwindEntities(); 
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			((NorthwindEntities)DataContext).SaveChanges();
		}
	}

    public partial class NorthwindEntities
    {
        private ObservableCollection<Product> _ProductsCollection;
        public ObservableCollection<Product> ProductsCollection
        {
            get
            {
                if (_ProductsCollection == null)
                {
                    _ProductsCollection = new ObservableCollection<Product>();
                    this.Products.ToList().ForEach(_ProductsCollection.Add);
                    _ProductsCollection.CollectionChanged += (s, e) => 
                    {
                        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                        {
                            var productToAdd = e.NewItems.OfType<Product>().FirstOrDefault();
                            this.AddToProducts(productToAdd);
                        }
                        else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
                        {
                            var productToDelete = e.OldItems.OfType<Product>().FirstOrDefault();
                            this.DeleteObject(productToDelete);
                        }
                    };
                }
                return _ProductsCollection;
            }
        }
    }
}
