I use MVVM pattern in my multithreading WPF app.
Now in the model I have (I skipped the obvious implementation of INotifyPropertyChanged interface to make it more clear):
public class ShallowModel : INotifyPropertyChanged
{
private string _dbState;
public string DbState
{
get { return _dbState; }
set
{
_dbState = value;
OnPropertyChanged("DbState") // ofc there is implementation of this
}
}
private InsideObject _inObject;
public InsideObject InObject
{
get { return _inObject; }
set
{
_inObject = value;
OnPropertyChanged("InObject")
}
}
}
public class InsideModel : INotifyPropertyChanged
{
private string _actState;
public string ActState
{
get { return _actState; }
set
{
_actState= value;
OnPropertyChanged("ActState")
}
}
}
Say I have TextBlocks on the View:
<TextBlock Text={Binding ActObjectState}/>
<TextBlock Text={Binding DbState}/>
Now there’s a part of problematic ViewModel:
public class ViewModel : INotifyPropertyChanged
{
private ShallowModel _model;
public string ActObjectState
{
get
{
if(_model.InObject != null)
return _model.InObject.ActState;
else
return null;
}
}
public string DbState
{
get
{
return _model.DbState;
}
}
}
The problem is that ActObjectState and DbState are not being updated when background thread is updating properties of ShallowModel and/or InsideModel. My questions are:
-
Should I add Model public property to ViewModel and bind view like {Binding Path=Model.DbState}? I think it disrupts the MVVM idea – View shouldnt know about Model.
-
InObject in ShallowModel is created by a new thread after User click button on UI. Therefore when ViewModel is created InObject is null. Somehow – after it’s created by the thread – ActObjectState is not updated. How to make it work? Make binding like {Binding Path=Model.InObject.ActState}? This implies the need of having knowledge about Model by UI designer.
Thx, sry for my english
i would take your suggestion 1. its the easiest way and i dont see any violation of the MVVM pattern.
if this not works for you – you have to put the view related logic in your viewmodel. so maybe its necessary that the viewmodel listen to the changes of the model and rethrow(with the view related logic) these changes to the view.
when working with threads be aware of dispatcher stuff, but i think you know that