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

namespace WPF.SaveLoadXML
{
    public class GridViewSelectionBehaviour
    {
        private RadGridView radGridView = null;

        public GridViewSelectionBehaviour(RadGridView radGridView)
        {
            this.radGridView = radGridView;
        }

        public static readonly DependencyProperty SelectedIndexProperty
            = DependencyProperty.RegisterAttached("SelectedIndex", typeof(int), typeof(GridViewSelectionBehaviour),
                new PropertyMetadata(-1, new PropertyChangedCallback(OnSelectedIndexPropertyChanged)));

        public static void SetSelectedIndex(DependencyObject dependencyObject, int value)
        {
            dependencyObject.SetValue(SelectedIndexProperty, value);
        }

        public static object GetSelectedIndex(DependencyObject dependencyObject)
        {
            return dependencyObject.GetValue(SelectedIndexProperty);
        }

        private static void OnSelectedIndexPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            RadGridView radGridView = dependencyObject as RadGridView;
            if (radGridView != null)
            {
                if (((int)e.NewValue) >= 0)
                {
                        // Create new GridViewFilterRow and attach RowLoaded event.
                        GridViewSelectionBehaviour bh = new GridViewSelectionBehaviour(radGridView);
                        bh.Attach();
                }
            }
        }

        private void Attach()
        {
            if (radGridView != null)
            {
                this.radGridView.Loaded += new RoutedEventHandler(radGridView_Loaded);
            }
        }

        void radGridView_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.radGridView.Items.Count > (int)GetSelectedIndex(this.radGridView))
            {
                var selectedItem = this.radGridView.Items[(int)GetSelectedIndex(this.radGridView)];

                if (selectedItem != null)
                {
                    this.radGridView.SelectedItem = selectedItem;
                }
            }
        }


    }
}
