To make DataBindings work, you must implement INotifyPropertyChange in a class that contains your bool value. If you hit myValue from a thread other than the user interface thread, you will have to use the SynchronizationContext and initialize myObject in the user interface thread.
public class myObject : INotifyPropertyChanged { // The class has to be initialized from the UI thread public SynchronizationContext context = SynchronizationContext.Current; bool _myValue; public bool myValue { get { return _myValue; } set { _myValue = value; // if (PropertyChanged != null) // PropertyChanged(this, new PropertyChangedEventArgs("myValue")); if (PropertyChanged != null) { context.Send( new SendOrPostCallback(o => PropertyChanged(this, new PropertyChangedEventArgs("myValue")) ), null); } } } public event PropertyChangedEventHandler PropertyChanged; }
Then set your DataBinding as follows:
checkBox1.DataBindings.Add("Checked", myObject.GlobalObject, "myValue");
The first parameter is the property of the UI object with which you want to bind. The second attribute is an instance of your target, the third is the name of the property of the target, which must be bound to the first.
I tried my best to flip your script using a timer that switches myValue every second (to check the checkbox accordingly). Here is the code of the form used:
System.Timers.Timer x = new System.Timers.Timer(); myObject target; public Form1() { InitializeComponent(); target = new myObject(); x.Elapsed += (s, e) => { target.myValue = !target.myValue; }; x.Interval = 1000; checkBox1.DataBindings.Add("Checked", target, "myValue"); x.Start(); }
source share