下面的代碼是我的問題的簡化版本:多線程應用程序上的數據綁定?
public partial class Form1 : Form
{
BackgroundWorker bw;
Class myClass = new Class();
public Form1()
{
InitializeComponent();
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
label1.DataBindings.Add("Text", myClass, "Text", true, DataSourceUpdateMode.Never);
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
myClass.Text = "Hi";
}
private void button1_Click(object sender, EventArgs e)
{
bw.RunWorkerAsync();
}
}
public class Class : INotifyPropertyChanged
{
private string _Text;
private void SetText(string value)
{
if (_Text != value)
{
_Text = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public string Text
{
get { return _Text; }
set { SetText(value); OnPropertyChanged(new PropertyChangedEventArgs("Text")); }
}
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null) PropertyChanged(this, e);
}
}
什麼情況是,當我點擊Button1的(它調用button1_Click
)在label1
文本不更新。這是因爲label1.Text
屬性在內部試圖從我的BackgroundWorker
的線程中更改,該線程會在內部導致異常。一般來說,解決這類問題最好的辦法是什麼?如果您必須從不同的線程更新Class.Text
屬性,但還必須具有綁定的控件,那麼將更改此代碼的哪一部分?
只有在* BGW完成後綁定*。使用RunWorkerCompleted事件。 – 2011-02-08 20:06:22