c# - Binding to a new instance of an object -
i trying figure out how create new instance of object without breaking xaml bindings. right i'm working observablecollection i'll call:
container.myclass.mycollection in viewmodel (with inpc implemented via kind of magic):
public observablecollection<myobject> collection { { return container.myclass.mycollection; } } in view:
<stackpanel> <textblock text="{binding collection.count}" /> <itemscontrol itemssource="{binding collection}"> <itemscontrol.itemspanel> <itemspaneltemplate> <uniformgrid columns="1" /> </itemspaneltemplate> </itemscontrol.itemspanel> <itemscontrol.itemtemplate> <datatemplate> <button content="{binding name}" /> </datatemplate> </itemscontrol.itemtemplate> </itemscontrol> </stackpanel> so, if try 'fresh' instance of class, can call , have bindings remain intact:
public void workingsomewhatfreshinstance() { container.myclass.mycollection.clear(); container.myclass.mycollection.add(new myobject() { name = "test1" }); container.myclass.mycollection.add(new myobject() { name = "test2" }); } however, if call method:
public myclass brokenfreshinstance() { var myclass = new myclass(); myclass.mycollection.add(new myobject() { name = "test1" }); myclass.mycollection.add(new myobject() { name = "test2" }); return myclass; } and then:
container.myclass = initialize.brokenfreshinstance(); the bindings no longer update. there way use new instance of object , have xaml bindings remain intact?
you can tell view refresh binding new instance calling propertychanged on observable:
public observablecollection<myobject> collection { { return _collection; } set { _collection = value; raisepropertychangedevent("collection"); } } you need assign collections property trigger event:
collection = container.myclass.mycollection; //this trigger propertychangedevent ... container.myclass = initialize.brokenfreshinstance(); collection = container.myclass.mycollection; // trigger again.. or can raise change manually doing:
container.myclass = initialize.brokenfreshinstance(); raisepropertychangedevent("collection");
Comments
Post a Comment