I have a windows form ‘MyForm’ with a text box that is bound to a property in another class ‘MyData’. The Data source update mode is set to “On Property Change”
I used the VisualStudio IDE. It created the following code for the binding
this.txtYield.DataBindings.Add(new Binding("Text", this.BindingSourceMyDataClass, "PropertyInMyDataClass", true, DataSourceUpdateMode.OnPropertyChanged));
In the form constructor, after initialize values code was added to bind the MyData Class to the form
myDataClassInstantiated = new MyDataClass();
BindingSourceMyDataClass.DataSource = myDataClassInstantiated;
The INotifyProperty Interface has been implemented:
public double PropertyInMyDataClass
{
get { return _PropertyInMyDataClass; }
set
{
if (!Equals(_PropertyInMyDataClass, value))
{
_PropertyInMyDataClass = value;
FirePropertyChanged("PropertyInMyDataClass");
}
}
}
A background worker is used to run the calculations and update the property ‘PropertyInMyDataClass’
I expected that the text box on the form would update automatically when the background worker completed. That didn’t happen
If I manually copy assign the value from the property to the form text box, the value is displayed properly
this.txtYield.Text = String.Format("{0:F0}", myDataClassInstantiated.PropertyInMyDataClass);
I tried to add Refresh() and Update() to the MyForm.MyBackgroundWorker_RunWorkerCompleted method, but the data still is not refreshed.
If I later run a different background worker that updates different text boxes on the same form, the text box bound to PropertyInMyDataClass gets updated
I would appreciate suggestions that will help me to understand and resolve this databinding problem
The problem comes from a couple of angles. If you are running the process on a background thread, the background thread cannot directly access a control on your form (which lives in a different thread) directly, otherwise you will get an exception. You also cannot expect the UI thread to update based on states in the background thread, unless you wire it up to do so. In order to do this, you need to invoke a delegate on the main UI thread..
Place this code (modify it to update whatever control you want with whatever value type you want) on the UI form.
Then you can call this function in your background worker thread. (assuming your background process function lives in the same form, you can call it directly), if not then you will need a reference to the UI form in the class that the background process runs in.