There seems to be conflicting thoughts on whether INotifyPropertyChanged
should be implemented in the Model or not. I think that it should be implemented in the Vie
In my experience, Model
objects don't have to (and probably shouldn't) know that they are being constructed in a View
. Often, Model
objects are entities that should never be allowed to be in an invalid state. ViewModel
objects are the things that construct the Model
objects.
So, since you never want to create a person who is very old or very young, and every person needs a name, your Person
class might look like this:
public class Person {
public int Age { get; private set; }
public string Name { get; private set; }
public Person(int age, string name) {
if (age < 0 || age > 150) throw new ArgumentOutOfRangeException();
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException();
Age = age;
Name = name;
}
}
And your PersonViewModel
might look like this::
class PersonViewModel : INotifyPropertyChanged {
private int _Age;
private int _Name;
public int Age {
get { return _Age; }
set {
if (_Age.Equals(value)) return;
_Age = value;
RaisePropertyChanged("Age");
}
}
public string Name {
get { return _Name; }
set {
if (_Name.Equals(value)) return;
_Name = value;
RaisePropertyChanged("Name");
}
}
public Person CreatePerson() {
return new Person(_Age, _Name);
}
}
You can then put whatever values you want in your PersonViewModel
without worrying about creating an invalid Person
object. You can also implement validation in the PersonViewModel
that may be more strict than the validation in the Person
class (for example, restricting the age range to adults over 18 years old (see IDataErrorInfo)).