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 Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using System.Windows.Threading;

namespace RadGridView_WPF_NoXAML_1
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{

		public MainWindow()
		{
			InitializeComponent();
			clubsGrid.KeyboardCommandProvider = new CustomProvider(clubsGrid, this);
		}

		public class CustomProvider : DefaultKeyboardCommandProvider
		{
			private GridViewHeaderCell focusedCell = null;
			private FrameworkElement focusScope = null;
			private GridViewHeaderRow headerRow = null;
			private RadGridView grid = null;

			public CustomProvider(RadGridView grid, FrameworkElement focusScope)
				: base(grid)
			{
				this.grid = grid;
				this.focusScope = focusScope;
				grid.Dispatcher.BeginInvoke(new Action(() => { this.headerRow = grid.ChildrenOfType<GridViewHeaderRow>().FirstOrDefault(); }), DispatcherPriority.Loaded);
			}

			public override IEnumerable<ICommand> ProvideCommandsForKey(Key key)
			{
				var pendingCommands = base.ProvideCommandsForKey(key).ToList();
				if (key == Key.Tab)
				{
					var focusedElement = FocusManager.GetFocusedElement(focusScope) as FrameworkElement;
					if (focusedElement == grid && grid.CurrentCell.Column.DisplayIndex == 0)
						focusedCell = focusedElement.ParentOfType<GridViewHeaderCell>();
					if (headerRow.Cells.IndexOf(focusedCell) == headerRow.Cells.Count - 1 && Keyboard.Modifiers != ModifierKeys.Shift)
					{
						return pendingCommands;
					}
					pendingCommands.Clear();
				}
				return pendingCommands;
			}
		}
	}
}
