我有一个基类实现INotifyPropertyChanged:
protected void OnNotifyChanged(string pName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
Run Code Online (Sandbox Code Playgroud)
我有一个派生类,其属性Latitude如下:
private double latitude;
public double Latitude
{
get { return latitude; }
set { latitude = value; OnNotifyChanged("Latitude"); }
}
Run Code Online (Sandbox Code Playgroud)
我的派生类也有一个Fly操作方法Latitude.
我还有一个Form,其TextBox绑定到Latitude我的派生类:
txtLat.DataBindings.Clear();
txtLat.DataBindings.Add("Text", bindSrc, "Latitude");
Run Code Online (Sandbox Code Playgroud)
一个线程用于启动,Fly如下所示:
Thread tFly = new Thread(f.Fly);
tFly.IsBackground = true;
tFly.Start();
Run Code Online (Sandbox Code Playgroud)
当Latitude改变,一个异常被抛出:
DataBinding cannot find a row in the list …
下图显示了我的代码的工作原理.当我按下按钮2时,列表框会更新,但不会在我按下按钮1时更新.为什么?
伪代码http://i44.tinypic.com/mj69oj.gif
问题线程是否相关?如果是,我应该在哪里添加对(Begin)Invoke的调用?
需要注意的一件有趣的事情是,如果我先按下button1然后按下按钮2,则单击button2时会显示button1单击生成的数据.所以似乎doFoo生成的数据在某处缓冲,然后在按下button2后推送到列表框.
编辑:
我尝试将AddNumber添加到表单代码中,并在listBox1.InvokeRequired返回true时添加对Invoke的调用.这解决了问题,但不是最好的设计.我不希望GUI必须"担心"如何将项添加到模型的一部分列表中.
如何在添加到列表类内部列表的同时保持逻辑,同时在列表更改时仍然更新gui?
编辑2:
现在我们已经确认这是一个线程问题,我已经更新了图像,以便更接近地反映我正在处理的实际代码的设计.
虽然Lucero的建议仍然解决了这个问题,但我希望能找到一些不需要表格来了解dll或CDllWrapper的东西.
模型(ListBoxDataBindingSource等)应该对视图(列表框,按钮,标签等)一无所知