Search code examples
c#wpfmvvminotifypropertychanged

INotifyPropertyChanged inside a Model when needing multiple instances of that class WPF


I have a ListView and the ItemTemplate of the ListView contains a TextBox. The ItemSource of the ListView is an ObservableCollection of type T of which the Viewmodel has an instance of as Property. The View needs to bind itself to a particular Property of T. (with T existing out of multiple Properties)

        <ListView ItemSource={Binding SomeObservableCollectionOfTypeT}>
           <ListView.ItemTemplate>
              <DataTemplate>
                   <TextBox Text = {Binding T.Someproperty, UpdateSourceTrigger=PropertyChanged} />
              </DataTemplate>
           </ListView.ItemTemplate>
        </ListView>

At first I had T as an inner class inside the ViewModel (with T also implementing INotifyPropertyChanged) but I realised I needed this class in multiple ViewModels in an identical fashion. T would be the model here.

I'm inclined to avoid using INotifyPropertyChanged in the Model as I think it is desirable having the View bind to the Viewmodel exclusively. Is this the exact scenario where using INotifyPropertyChanged is valid in Models? How should I approach this situation in a typical situation like this, where you need to bind to Properties of a Type that is inside a collection in your ViewModel using the MVVM Design pattern?


Solution

  • I'm inclined to avoid using INotifyPropertyChanged in the Model as I think it is desirable having the View bind to the Viewmodel exclusively.

    It depends on how you define a "model". If it's some kind of domain object that is used across several applications, you should not bind directly against it but instead create a wrapper view model class that does implement INotifyPropertyChanged.

    Is this the exact scenario where using INotifyPropertyChanged is valid in Models?

    Certainly as long as the "model" is not a domain object. Then you should replace it with a view model in your client application.

    How should I approach this situation in a typical situation like this, where you need to bind to Properties of a Type that is inside a collection in your ViewModel using the MVVM Design pattern?

    Create a "child" view model class that implements INotifyPropertyChanged and translate the current model objects to this type, for example by simply wrapping the properties.