c# - Binding to the same property on multiple windows doesn't work -


i ran quite confusing problem when developing multi-window wpf application.

there 2 windows, mainwindow , secondwindow. code of both pretty simple: mainwindow:

<button content="change property 5" click="changeproperty" horizontalalignment="left" margin="10,10,0,0" verticalalignment="top" /> 

secondwindow:

<label content="{binding instanceofmyclass.value, notifyonsourceupdated=true}"></label> 

the code behind second window untouched, code behind first window following:

public partial class mainwindow : window {     secondwindow w;     viewmodel vm;     public mainwindow()     {         initializecomponent();         vm = new viewmodel() { instanceofmyclass = new myclass() { value = 3 } };         w = new secondwindow() { datacontext = vm };         w.show();     }      private void changeproperty(object sender, routedeventargs e)     {         vm.instanceofmyclass.value = 7;     } } 

and view model class implements inotifypropertychanged:

class viewmodel : inotifypropertychanged {     private myclass _instance;     public myclass instanceofmyclass      {                 {             return _instance;         }         set         {             _instance = value;             onpropertychanged("instanceofmyclass");         }     }      public event propertychangedeventhandler propertychanged;     protected virtual void onpropertychanged(string propertyname)     {         var handler = propertychanged;         if (handler != null) handler(this, new propertychangedeventargs(propertyname));     } } class myclass {     public int value { get; set; } } 

i expected text block change text 5 when click button. number "3" correctly loaded on startup. window refreshes when create new instance of myclass , set instanceofmyclass in viewmodel.

but when hit button - or, stranger, when temporarily store instanceofmyclass, set null , reassign saved variable - nothing happens.

any idea why?

thanks in advance!

implement inotifypropertychanged in myclass , try again. in changeproperty change value property, doesn't notify view change.

or can try rewriting changeproperty following:

vm.instanceofmyclass = new myclass() { value = 7 }; 

both of these approaches should fix problem far can see.


Comments