I am trying to understand the MVVM concept better and I am struggling with the model and viewmodel relation.
Can I say that: The Model is not aware of the ViewModel as the ViewModel is not aware of the View?
Correct me if I am wrong, considering a simple WPF application that displays some string we should have:
View: XAML TextBlock bound to string property text1
XAML.CS instantiates ViewModel vModel
ViewModel: has property text1
implements INotifyPropertyChanged notifying View of its changes
instantiates Model mModel
Model: has property string text1
?? implements INotifyPropertyChanged notifying ViewModel of its changes ??
Here I am confused about the last part. If the whole logic happens in model, e.g string manipulation, how to handle notification from Model in ViewModel?
Is it possible that ViewModel_PropertyChanged can access and change it's property value through property name? And I don't mean:
if (e.PropertyName == "text1")
As it will be a nightmare if we have a lot of properties
Assuming that the property has the same name in Model and ViewModel we could do:
// Model PropertyChanged Handler
private void mainModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyPropertyChanged(e.PropertyName);
}
// ViewModel PropertyChanged Notifier
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Then ViewModel could hold a pass-thought property
public string text1
{
get { return mModel.text1; }
set { }
}
But is that correct? And what if we need this property to be changed from UI?:
public string text1
{
get { return mModel.text1; }
set
{
if (mModel.text1 != value)
{
mModel.text1 = value;
NotifyPropertyChanged("text1"); // ??
}
}
}
mModel.text1 = value; - this will notify everybody including UI about the change that it has made NotifyPropertyChanged("text1"); // ?? - this will reapeat this notification
If the ViewModel is holding only this pass-through properties, what is the need for it? Is the ViewModel needed only to make some different sense of the Model properties to display them in UI?
Sorry for the vast post, hope someone can help me.