Reading Josh Smiths article about MVVM his view model CustomerViewModel
implements INotifyPropertyChanged
but not the underlying Customer
class.
I can only see one (feasib开发者_运维技巧le) way to make change notification work in that case - only make changes to the CustomerViewModel
and not the Customer
. In that case, should the backend logic of my program also simply work against ViewModels? That seems pretty weird, they being View Models after all.
Anyone that can clarify this a bit?
Thanks!
Clarification:
Say that I've got a model Quote and a list of Quotes.
public class Quote
{
public string Name { get; set; }
public decimal Value { get; set; }
}
public QuoteViewModel : INotifyPropertyChanged
{
private Quote quote;
public event EventHandler PropertyChanged;
public decimal Value
{
get { return quote.Value; }
set
{
quote.Value = value;
PropertyChanged("Value");
}
}
}
Now, if Quote changes as a result of a background thread polling a web-service, the UI will not be notified of this, since Quote do not implement INotifyPropertyChanged, unless all parts of the system uses the ViewModel?
I'm guessing that in his example, he is using the notification to propagate changes to one part of the view to other parts of the view. Since the different portions are presumably bound to the same view-model, this would work.
Re logic validation; I probably wouldn't base that on change events anyway; firstly because that would be a lot of even subscriptions (contrast UI, where you only bind things the UI cares about), and secondly it is probably too important to risk missing ;p If the model isn't performing validation internally (as changes happen) then I would just run the validation logic explicitly before commit, looking at the members altogether. This also avoids the "briefly inconsistent" issue, i.e. where you plan to make several changes that result in a valid model, but if you validate immediately it is either really awkward to find a sequence that allows you to make the change you want, or is totally impossible. By deferring the validation, this goes away.
Marc makes some excellent points, but it sounds like you really need to modify the model outside of the context of your UI. Consider implementing INotifyPropertyChanged on your model, but as Marc mentioned, this will likely be a little problematic and certainly require significant testing. This approach would work best if your model is a POCO. If it can double as a psuedo-VM exposed in all the VMs that use it, then maybe you can minimize or eliminate VM->model event subscription:
public QuoteViewModel : INotifyPropertyChanged
{
private Quote quote;
public event EventHandler PropertyChanged;
public INotifyPropertyChanged Quote
{
get { return quote; }
set
{
quote = value;
PropertyChanged("Quote");
}
}
}
精彩评论