Monday, 15 June 2015

c# - Bind a textbox to a property class -



c# - Bind a textbox to a property class -

i have these :

a form label on it a class "business" a class "timerhelper"

i'd when update property mytime, update textbox too

my "business" class :

public class mybusinessclass : inotifypropertychanged { public void makesound(object sender, elapsedeventargs e) { // alter mytime here } public event propertychangedeventhandler propertychanged; private int mytime; public int mytime { { homecoming mytime; } set { mytime= value; invokepropertychanged(new propertychangedeventargs("mytime")); } } public void invokepropertychanged(propertychangedeventargs e) { propertychangedeventhandler handler = propertychanged; if (handler != null) handler(this, e); } }

the "timerhelper" :

public class timerhelper { private timer _timer; public void run() { _timer = new timer(1000); _timer.enabled = true; _timer.elapsed += new elapsedeventhandler(mybusinessclass.makesound); } }

in forms, tried :

mytextbox.databindings.add("text", new mybusinessclass(), "mytime");

but exception in method "invokepropertychanged"

i tried :

invoke((methodinvoker)delegate { mytextbox.text = new mybusinessclass().mytime; });

but textbox never updated

i think problem trying update text box through databibding other thread. mean, you're using system.timers.timer class invokes elapsed event in threadpool. databinding fails updating command because you're changing business class in threadpool. should alter of thread context in elapsed event handler , update business model in main thread (where text box created).

public class timerhelper { private timer _timer; public void run() { _timer = new timer(1000); _timer.enabled = true; _timer.elapsed += new elapsedeventhandler(ontimerelapsed); } } void ontimerelapsed (object sender, elapsedeventargs e) { if (mytextbox.invokerequired) { mytextbox.invoke(mybusinessclass.makesound); } }

}

c# .net winforms thread-safety

No comments:

Post a Comment