Monday, February 17, 2014

Update UI from ViewModel for INotifyCollectionChanged and INotifyPropertyChanged

Please see the example of loading trades data using ObservableCollection (which implements INotifyCollectionChanged) and reflecting updates in UI data grid automatically when trades are replaced with new trades here http://wpfgrid.blogspot.com/2014/02/simple-observablecollection-wpf-mvvm.html


Then please see how we have updated "Trade" class so that it implements INotifyPropertyChanged  interface here http://wpfgrid.blogspot.com/2014/02/inotifypropertychanged-implementation.html


Now if we replace the codes in the LoadTradeCommand's Execute method on fist example (top) with the following codes so that instead of every two seconds replacing with new trades data, it just updates the quantity and market price of the first time loaded trades every two seconds.




public void Execute(object parameter)
        {
            var loadedTrades = parameter as ObservableCollection<Trade>;
            if (loadedTrades != null)
            {
                TaskFactory taskfac = new TaskFactory();
                taskfac.StartNew(() =>
                    {
                        while (true)
                        {
                            var tradelist = Trades.LoadTradesFromDataSource();
                            App.Current.Dispatcher.Invoke(new Action(() =>
                            {
                                if (loadedTrades.Count == 0) // load only first time
                                {
                                    foreach (var trade in tradelist)
                                        loadedTrades.Add(trade);
                                }
                                else
                                {
                                    var mktpricetmp = DateTime.Now.Second; // just to get 
                                                                              some number

                                    var qtytmp = (DateTime.Now.Second + 5) * 1000; // just 
                                                                          to get some number



                                    foreach (var trade in loadedTrades)

                                    {

                                        trade.Qty = qtytmp.ToString();

                                        trade.MktPrice = mktpricetmp.ToString();

                                    }
                                }

                            }));

                            Thread.Sleep(2000);
                        }
                    });
            }


Now this will as well update data grid automatically as the trades data in the ObservableCollection are being updated.









Codes:

https://skydrive.live.com/#cid=BA4BC1E3D681B9B3&id=BA4BC1E3D681B9B3!112

No comments:

Post a Comment