I'm developing a MVVM WPF application with C# and .NET Framework 4.6.
I have this class:
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
I have implemented here INotifyPropertyChanged
because I don't want to implement it in all of my ViewModel classes.
To use this class, I use inherit:
public class Presenter : ObservableObject
{
private string _someText;
public string SomeText
{
get { return _someText; }
set
{
_someText = value;
RaisePropertyChangedEvent("SomeText");
}
}
}
But, is there a way to use ObservableObject
using object composition?
I understand object composition as instead of inherit, create a private object instance of ObservableObject
in class Presenter
.
I'm not sure if any ViewModel class should implement INotifyPropertyChanged
.
UPDATE:
This is not a duplicate question. I'm asking if a ViewModel has always to implement INotifyPropertyChanged
interface or instead, I can use Object composition. I have explained before. Please, read carefully my question.
Well, ... ViewModels are best to be viewed as Composition, but the notification part should be an implementation of the Interface (or in your case inheritance). You have your DTOs and your ViewModels would be a composition of the DTOs, depending on the scenario.
This implementation of the same stuff can be tedious, but for WPF is still necessary. What you can do to simplify the process is to use Veawrs like Fody. It changes your observation of the ViewModel. All of the properties of the VM are by default observable properties, but you exclude the ones you do not want to, or you can define for one property to let the UI know that it should also update others.
It keeps the code very clean and simple. You will not need to implement the Interface, but it will be inherited in build time if you give the class the needed attribute.