In our WPF/MVVM application, we are binding to property of the Model
directly because the Model
is from legacy library (we added the support of INotifyPropertyChanged
to the Model
class). I.e., the code of ViewModel
looks like
Public Class MyViewModel
Inherits ViewModelBase
Public Property Model As MyModel
End Class
And then the binding looks like this:
<TextBox Text="{Binding Model.Prop1}" />
Everyting worked fine until I have this requirement to have some properties in the ViewModel
which depend on Model.Prop1
. Specifically, I am binding the ItemSource
of one ComboBox
to a property of collection in the ViewModel
, and this collection should be refreshed/recalculated whenever Model.Prop1
is changed. The code looks like this:
<ComboBox ItemsSource="{Binding MyCollection}" />
I have some options but they are not good in my opinion:
- I can have
Model
class hold a reference ofViewModel
. And in the setter of Prop1 in theModel
I update the MyColleciton property ofViewModel
. Of course it is not a good idea - Use
EventAggregator
for the communication betweenModel
andViewModel
. Not efficient in my opinion plus I need to make big change in theModel
class too. - Let
ViewModel
have one propertyProp1
and bind to this. In the getter of it return Model.Prop1 and in the setter assignModelProp1 = Value
. This is my current solution but there is one problem: in ourModel
we have other property/attribute which are useful and we create a commonStyle
based on this property/attribute. For example, when the Model.Prop1 is changed, another property calledIsDirty
inModel
class is set toTrue
and in theView
we change the color. But if we use Prop1 fromViewModel
, instead of fromModel
, we lose this commonStyle
behavior like other properties.
So now I still want to use the binding to {Binding Model.Prop1}
(not create a wrapper property in the ViewModel
) but somehow notify other properties in the Model
when it is changed. Can I do that?