using System.Windows;
using System.Windows.Controls;
using Telerik.Windows.Controls;
using System.Collections.Generic;

namespace AddNewRowWithWindow
{
	public partial class MainPage : UserControl
	{
		PopupControl popup = new PopupControl();
		RadWindow wnd = new RadWindow();	
		
		public MainPage()
		{
			InitializeComponent();

			wnd.Content = popup;
			wnd.WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation.CenterOwner;
		}

		private void Button1_Click(object sender, RoutedEventArgs e)
		{								
			popup.DataContext = new Player();								
			wnd.Show();
			wnd.Closed += new System.EventHandler<WindowClosedEventArgs>(wnd_Closed);			
		}

		void wnd_Closed(object sender, WindowClosedEventArgs e)
		{
			RadWindow window = sender as RadWindow;

			if(window.DialogResult==true)
			{
				Player player = popup.DataContext as Player;
				var players = this.playersGrid.ItemsSource as IList<Player>;
				if(!players.Contains(player))
				{
					players.Add(player);
				}
				
				
				this.playersGrid.ScrollIntoView(player);
				this.playersGrid.SelectedItem = player;				
			}	
			else
			{
				Player player = popup.DataContext as Player;
				var players = this.playersGrid.ItemsSource as IList<Player>;
				players.Remove(player);
				
			}
					
		}

		private void playersGrid_AddingNewDataItem(object sender, Telerik.Windows.Controls.GridView.GridViewAddingNewEventArgs e)
		{
			e.Cancel = true;
			popup.DataContext = new Player();
			wnd.Show();
			wnd.Closed += new System.EventHandler<WindowClosedEventArgs>(wnd_Closed);			
		}
		
		
			
	}
}
