I have this code in my viewmodel (Singleton):
/// <summary>
/// Gets or sets the person list.
/// </summary>
/// <value>
/// The person list.
/// </value>
public BindingList<Person> PersonList
{
get { return personList; }
set
{
personList = value;
OnPropertyChanged(nameof(PersonList));
OnPropertyChanged(nameof(PersonCount));
}
}
/// <summary>
/// Gets the person count.
/// </summary>
/// <value>
/// The person count.
/// </value>
public int PersonCount
{
get
{
return personList.Count();
}
}
When I add a Person to the BindingList it appears in the view correctly. A Change of one of the items of BindingList is shown correctly. But the PersonCount is not updated and appears as "0".
The class Person is implemented like this:
public class Person : NotificationObject
{
#region Fields
private string name;
private DateTime birthDate;
private string lastName;
#endregion // Fields
#region Construction
#endregion // Construction
#region Attributes
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged(nameof(Name));
}
}
public string LastName
{
get { return lastName; }
set
{
lastName = value;
OnPropertyChanged(nameof(LastName));
}
}
public DateTime BirthDate
{
get { return birthDate; }
set
{
birthDate = value;
OnPropertyChanged(nameof(BirthDate));
OnPropertyChanged(nameof(Age));
}
}
public int Age
{
get { return (DateTime.Now - birthDate).Days/365; }
}
#endregion // Attributes
#region Operations
#endregion // Operations
#region Implementation
#endregion // Implementation
} // class Person
Why the PersonCount is not updated and how to do it right? What I am doing wrong?
Thanks in advance, Andreas
The problem in your code is, once you bind the 'PersonList' to the view model, the list object doesn't change unless you bind another list (what happens is just items are added or removed from the list), therefore the setter of the 'PersonList' property is not called & therefore "Notify property changed" doesn't trigger for 'PersonCount'.
However as the 'PersonList' is a BindingList, added/removed items are reflected in the UI.
Solutions
1) Register 'PersonList' to ListChanged event and call 'Notify Property Changed' in the event handler.
public BindingList<Person> PersonList
{
get { return personList; }
set
{
if (personList != null)
personList.ListChanged -= PersonList_ListChanged;
personList = value;
if (personList != null)
personList.ListChanged += PersonList_ListChanged;
OnPropertyChanged(nameof(PersonList));
}
}
public PersonsDashboardViewModel()
{
PersonList = new BindingList<Person>();
PersonList.Add(new Person("Name1", "Lname1"));
PersonList.Add(new Person("Name2", "Lname2"));
}
private void PersonList_ListChanged(object sender, ListChangedEventArgs e)
{
OnPropertyChanged(nameof(PersonCount));
}
OR
2) Call 'Notify Property Changed' for 'PersonCount' where you add person items.
public void AddPersonItem()
{
PersonList.Add(new Person("Sean", "Brendon"));
OnPropertyChanged(nameof(PersonCount));
}