DataBindings を機能させるには、bool 値を含むクラスにINotifyPropertyChangeを実装する必要があります。UI スレッド以外のスレッドから myValue をヒットしている場合は、SynchronizationContext を使用して、UI スレッドで myObject を初期化する必要があります。
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;
}
次に、DataBinding を次のように設定します。
checkBox1.DataBindings.Add("Checked", myObject.GlobalObject, "myValue");
最初のパラメーターは、バインド先の UI オブジェクトのプロパティです。2 番目の属性はターゲット オブジェクトのインスタンスで、3 番目は最初の属性にバインドする必要があるターゲット オブジェクトのプロパティ名です。
毎秒 myValue を切り替えるタイマーを使用してシナリオを反映するために最善を尽くしました (それに応じてチェックボックスをオンにします)。使用したフォームのコードは次のとおりです。
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();
}