Model does not implement INotifyPropertyChanged

In the context of the MVVM pattern, how to structure the ViewModel when the models don't implement the INotifyPropertyChanged interface?

I like to keep my models as simple as possible and to implement the INotifyPropertyChanged interface just for binding purposes seems like an unwanted complexity. So in most cases I require my VMs to wrap model properties like in the following example:

class ViewModel : INotifyPropertyChanged
{
    private Model model;

    public int MyProperty
    {
        get { return model.MyProperty; }
        set
        {
            if (value != model.MyProperty)
            {
                model.MyProperty = value;

                // Trigger the PropertyChanged event
                OnPropertyChanged("MyProperty");
            }
        }
    }

    /* ... */
}

      

This will make the bindings work fine, including double-sided.

Now, what happens if the command executes a model method with complex logic (affecting the value of many properties of different objects)? The model does not implement INotifyPropertyChanged, so we cannot know that it has been updated. The only solution that comes to my mind is to use messaging (mediator pattern) to inform all VMs about the execution of the method so that each VM fires a PropertyChanged event for every potentially affected property:

// Sample ICommand.Execute() implementation
public void Execute(object parameter)
{
    var model = (Model)parameter;

    model.VeryComplexMethod();

    // Just an example, the string "VeryComplexMethodExecuted" is
    // sent to all listening VMs. Those VMs will in turn fire the
    // PropertyChanged event for each property that may have changed
    // due to the execution of the complex model method.
    Messaging.Broadcast("VeryComplexMethodExecuted");
}

      

Share your ideas, thanks.

+3


source to share


1 answer


Declare your users virtual and use something like Castle Dynamic Proxy to automatically notify you of changes:

http://ayende.com/blog/4106/nhibernate-inotifypropertychanged



This must be used with care when your models are instantiated in your data layer because it returns a completely new instance. Your database code will think the object has changed and serialize it again, which in turn will have a huge performance impact. Fortunately, all good ORMs provide replacement mechanisms in wrapper classes at creation time.

0


source







All Articles