wpf - Raising OnPropertyChanged in the setter of each property vs Instance of Object -
information question:
i trying understand how implement inotifypropertychanged on objects , collections.
first, here viewmodelbase class:
public abstract class viewmodelbase : inotifypropertychanged { public event propertychangedeventhandler propertychanged; protected virtual void onpropertychanged([callermembername] string propertyname = "") { var handler = propertychanged; if (handler != null) { handler(this, new propertychangedeventargs(propertyname)); } } } consider have class called person:
public class person { public int id { get; set; } public string name { get; set; } public string age { get; set; } } to use inotifypropertychanged, examples have seen change person class this:
public class person { public int id { get; set; } private string _name; public string name { { return _name; } set { _name = value; onpropertychanged(); } } private string _age; public string age { { return _age; } set { _age = value; onpropertychanged(); } } } it seems work same when used single time on instance of object (this might useful if there lot of properties):
private person _person; public person myperson { { return _person; } set { _person = value; onpropertychanged(); } } actual question:
1 - make difference (aside amounts of code) whether call onpropertychanged() on each individual property verses on instance of object? (are both considered practice?)
2 - if setting onpropertychanged() on object instance practice, correct create observablecollection this?:
var personcollection = new observablecollection<myperson>();
1) well, if want call on object instance, need every time use class in binding. when implement onnotifypropertychanged directly inside class, don't need care later on...
2) classes inotifypropertychanged not require observable collections. must when binding colection ui control (listbox, listview) , want add/remove elements. observable collection make sure ui gets updated.
Comments
Post a Comment