-1
\$\begingroup\$

I have been starting to learn MVVM to give my WPF projects better structure.

I have to sample classes, DeviceModel and DeviceViewModel. Currently it is set up so that the model is exposed as a property within the view model. The model can then be bound to directly in the view.

public DeviceModel Device
{
    get { return device; }
    set
    {
        device = value;
        OnPropertyChanged();
    }
}

I am looking for feedback to taking this approach over alternative approaches in MVVM. Specifically more traditional approaches such as exposing each of the model's properties as properties within the view model that then just update the values stored in the model.

An example of this would look like the following.

public string DeviceName
{
    get {return device.DeviceName; }
    set
    {
        device.DeviceName = value;
        OnPropertyChanged();
    }
}
\$\endgroup\$
  • \$\begingroup\$ I'm afraid I do not have enough rep to vote to take this question off hold but I believe I have edited the question so that it meets site requirements \$\endgroup\$ – Dan Jul 31 '18 at 7:42
1
\$\begingroup\$

Models typically do not implement INotifyPropertyChanged interface. So binding directly to model properties has two main consequences:

1) It creates a memory leak.

2) It disables ViewModel -> View notifications. Models do not fire PropertyChanged event, so UI will not update itself when you change model properties from code. Updates coming in the opposite direction (from UI to your model) will still work though.


Your approach will work fine, if your DeviceModel is immutable. Meaning that you update it as

//setter fires PropertyChanged event
Device = new DeviceModel(...);

Then you can use OneTime binding in xaml to avoid memory leaks

<Border DataContext="{Binding Device}">
    <TextBlock Text="{Binding SomeDeviceProperty, Mode=OneTime}"/>
</Border>
\$\endgroup\$
  • \$\begingroup\$ Thanks for the answer. That makes more sense now \$\endgroup\$ – Dan Jul 30 '18 at 14:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.