using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Data;

namespace AddNewRowAndFocusFirstCell
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public CollectionViewSource Source { get; set; }
        public ObservableCollection<MyClass> list = new ObservableCollection<MyClass>();
        public MainWindow()
        {
            InitializeComponent();
            this.Source = new CollectionViewSource();
            //var list = new ObservableCollection<MyClass>();
            for (int i = 0; i < 10; i++)
            {
                var item = new MyClass { MyProp2 = i, MyProperty = i * 10 };
                list.Add(item);
            }
            Source.Source = list;
            this.DataContext = Source.View;
        }

        MyClass dd = new MyClass { MyProp2 = 4, MyProperty = 40 };
        int i = 0;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.PricingGrid.BeginInsert();
        }

        private void PricingGrid_AddingNewDataItem(object sender, Telerik.Windows.Controls.GridView.GridViewAddingNewEventArgs e)
        {
            dd = new MyClass { MyProp2 = 4 + i, MyProperty = 40 + i };
            i++;

            var insertionIndex = 0;
            for (int j = 0; j < list.Count; j++)
            {
                if (list[j].MyProperty > dd.MyProperty)
                {
                    insertionIndex = j;
                    break;
                }
            }

            list.Insert(insertionIndex, dd);

            e.Cancel = true;
            e.NewObject = dd;

            PricingGrid.ScrollIntoView(e.NewObject);
            PricingGrid.SelectedItem = e.NewObject;
            PricingGrid.BeginEdit();
        } 

    }
    public class MyClass
    {
        public int MyProperty { get; set; }
        public int MyProp2 { get; set; }
    }
}
