I have a WPF window that allows the user to edit the Date of Birth of an employee, in this window is also a TextBox to display the age from the DoB entered.
The DoB textbox is bound to my EmployeeModel Dob property
The Age textbox is bound to my EmployeeModel Age property and cannot be set, and the get using the Dob value.
The problem I'm facing is when the user changes the DoB, the Age textbox does not get updated.
I have found that if I implement INotifyPropertyChanged
in my EmployeeModel, and add OnPropertyChanged("Age")
in the Dob property, then the Age value gets updated. But this goes against what I have been advised that my Models should be business logic only and should not implement INotifyPropertyChanged.
How should I set this up so Age updates when DoB is changed without modifying the Model?
EmployeeModel
class EmployeeModel
{
public DateTime? Dob { get => _dob; set => _dob = value; }
public int Age
{
get
{
if (_dob == null)
return 0;
DateTime now = DateTime.Today;
int age = now.Year - _dob.Value.Year;
if (now < _dob.Value.AddYears(age))
age--;
return age;
}
}
}
EmployeeViewModel
class EmployeeViewModel : INotifyPropertyChanged
{
private EmployeeModel _employee;
public EmployeeModel Employee
{
get => _employee;
set
{
if (_employee != value)
{
_employee = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName]string caller = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
View
<Label Content="DOB" />
<DatePicker SelectedDate="{Binding Employee.Dob, TargetNullValue=''}" />
<Label Content="Age" />
<TextBox Text="{Binding Employee.Age, Mode=OneWay}" />