3

I'm new to WPF and MVVM and I started with "Jason Dolinger on Model-View-ViewModel" article and example but I have some questions regarding databinding.

1) In his demo application, he's subclassing DependencyObject for the ObservableCollection Items. What are the pros/cons compared to INotifyPropertyChanged ?

2) What is the best way to update the view from the model in a datagrid/listview ? In his example, he registers as a listener when a Quote object is added or updated :

_source.QuoteArrived += new Action<Quote>(_source_QuoteArrived);

Than the ViewModel creates and adds the QuoteViewModel object to the collection OR updates the view by setting the updated Quote object in the convenient QuoteViewModel object using a dictionary called _quoteMap.

void _source_QuoteArrived(Quote quote)
{

    QuoteViewModel qvm;
    if (_quoteMap.TryGetValue(quote.Symbol, out qvm))
    {
        qvm.Quote = quote;
    }
    else
    {
        qvm = new QuoteViewModel();
        qvm.Quote = quote;

        this.Quotes.Add(qvm);

        _quoteMap.Add(quote.Symbol, qvm);
    }
}   

Is there a better way to update the view from the model when a Quote object has been updated or am I forced to create a dictionnary ? It would be so easier if the listview could be updated immediately when a Quote object is updated... without having Quote to subclass INotifyPropertyChanged or DependencyObject.

Thanks

LPL
  • 16,827
  • 6
  • 51
  • 95
Hervé Donner
  • 523
  • 1
  • 6
  • 13

1 Answers1

1

For your first question, see this StackOverflow question. Generally people seem to prefer INotifyPropertyChanged.

As for your second question, given that quotes can arrive at any time, you need some method of mapping the quotes that arrive to the quotes you already have in your collection. Using a dictionary seems a sensible way to do this. How else would you suggest?

You state that it would be nice for the ListView to be updated immediately, but how does the ListView know what object the new Quote corresponds to? The ListView purely watches a collection that implements INotifyCollectionChanged, it knows nothing about the internals of Quote, or Quote.Symbol

Community
  • 1
  • 1
GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103
  • Maybe I could create an event in my MainWindowViewModel and fire this event when a Quote is updated. Than I can listen to that event in my MainWindow and call dataGrid1.Items.Refresh(); Is it a good idea ? – Hervé Donner Apr 23 '12 at 11:41
  • But that will refresh the entire grid every time one item updates Won't that lose any edits that are in place? (Never used Grid) – GazTheDestroyer Apr 23 '12 at 12:36