Reputation: 972
SHORT
When it comes to MVVM, is it legal to have a ViewModel in a Model class due to polymorphism?
DETAILED
Imagine you have the following construct of 2 classes:
public class ArticleModel
{
public string Name { get; set; }
}
public class TransactionModel
{
public ArticleModel ArticleModel { get; set; }
}
So basically every transaction has an associated article. Therefore, if you wrap this in a ViewModel, it may look as follows:
ArticleViewModel
public class ArticleModelView
{
private ArticleModel _ArticleModel;
public ArticleModel ArticleModel
{
// basic get and set + notify
}
public string Name
{
// basic get and set + notify
}
}
TransactionViewModel
public class TransactionViewModel
{
private TransactionModel _TransactionModel;
public TransactionModel TransactionModel
{
// basic get and set + notify
}
public ArticleModel ArticleModel
{
// basic get and set + notify
}
}
The reason I'm asking is, if you declare a TransactionViewModel
with a TransactionModel
, you won't get the updates of the underlying ArticleModel
. For example:
TransactionViewModel transactionViewModel = new TransactionViewModel
(new TransactionModel(new ArticleModel("sometestname")));
Now, when changing the name of the underlying ArticleModel
:
transactionViewModel.ArticleModel.Name = "hi";
nothing will be notified of the changes made since I did not assign a new ArticleModel
but instead just changed the name attribute.
If the ArticleModel
property in TransactionModel
would be an ArticleViewModel
, the changes would have been reported. I could even implement a ArticleViewModel
in the TransactionViewModel
but then there could be still the chance that due to wrong access the changes may not be reported.
Any thoughts on this?
Upvotes: 0
Views: 59
Reputation: 4122
So it looks like you are trying to change the articlemodels name property but also notifyproperty change, which the way you are doing it won't work unless your model implements the inotifypropertychange. What you could do is somehting like:
public class TransactionViewModel
{
public ArticleModel CurrentArticleModel { get; set; }
public String Name
{
get { return CurrentArticleModel.Name; }
set
{
CurrentArticleModel.Name = value;
NotifyPropertyChange("Name");
}
}
Also if necessary, I don't see anything wrong with your TransactionViewModel having an instance of a ArticleViewModel. I would assume that the ArticleViewModel would be bound to its own usercontrol or something though
Upvotes: 1