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

namespace SilverlightApplication1
{
    public class MyDataContext
    {
        string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random rnd;

        ObservableCollection<StockData> _Source;
        ObservableCollection<StockData> Source
        {
            get
            {
                if (_Source == null)
                {
                    rnd = new Random();

                    _Source = new ObservableCollection<StockData>(from i in Enumerable.Range(0, 50) select CreateStockData());

                    DispatcherTimer timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromMilliseconds(1);
                    timer.Tick += new EventHandler(timer_Tick);
                    timer.Start();
                }

                return _Source;
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            int index = rnd.Next(0, Source.Count);

            StockData item = CreateStockData(); // create new item.

            Source[index] = item; // replace the old  item.
        }

        private StockData CreateStockData()
        {
            StockData item = new StockData();
            item.Name = String.Format("{0}{1}{2}{3}", letters[rnd.Next(0, letters.Count())], letters[rnd.Next(0, letters.Count())], 
                letters[rnd.Next(0, letters.Count())], letters[rnd.Next(0, letters.Count())]);
            item.LastUpdate = DateTime.Now;
            item.Change = rnd.NextDouble();
            return item;
        }

        QueryableCollectionView _Data;
        public QueryableCollectionView Data
        {
            get
            {
                if (_Data == null)
                {
                    _Data = new QueryableCollectionView(Source);
                    _Data.SortDescriptors.Add(new SortDescriptor()
                    {
                        Member = "Name",
                        SortDirection = System.ComponentModel.ListSortDirection.Descending
                    });
                }

                return _Data;
            }
        }
    }

    public class StockData
    {
        public string Name { get; set; }
        public double Change { get; set; }
        public DateTime LastUpdate { get; set; }
    }
}
