为了解释这个问题,我把所需的一切都放在一个小样本应用程序中,希望能够解释这个问题 我真的试图尽可能减少所有内容,但在我的实际应用中,这些不同的演员彼此不认识,也不应该.因此,简单的回答,如"将变量放在上面的几行并调用它上面的Invoke"是行不通的.
让我们从代码开始,然后再解释一下.首先有一个实现INotifyPropertyChanged的简单类:
public class MyData : INotifyPropertyChanged
{
private string _MyText;
public MyData()
{
_MyText = "Initial";
}
public string MyText
{
get { return _MyText; }
set
{
_MyText = value;
PropertyChanged(this, new PropertyChangedEventArgs("MyText"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Run Code Online (Sandbox Code Playgroud)
所以没什么特别的.这里的示例代码可以简单地放入任何空的控制台应用程序项目中:
static void Main(string[] args)
{
// Initialize the data and bindingSource
var myData = new MyData();
var bindingSource = new BindingSource();
bindingSource.DataSource = myData;
// Initialize the form and the controls of it ...
var form …Run Code Online (Sandbox Code Playgroud) 我有一个班,比如说人,有一个Id和一个名字.该类正确实现了INotifyPropertyChanged
另外:有人要求上课人.
我真正的问题是一个更复杂的课程,我把它简化为一个相当简单的POCO,以确定它不是因为我的班级.
本来:
public class Person
{
public int Id {get; set;}
public string Name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
对于更新,它需要实现INofityChanged.完整的代码就在这个问题的最后
StackOverflow:如何正确实现INotifyPropertyChanged
到现在为止还挺好.如果在单独的线程中更改Person,则会出现问题.
我经常收到带有消息的InvalidOperationException
BindingSource不能是自己的数据源.不要将DataSource和DataMember属性设置为引用BindingSource的值.
我想这与更新是在一个等待的异步任务中完成的事实有关.我知道在更新用户界面项之前,您应该检查InvokeRequired是否相应地采取行动.
private void OnGuiItemChanged()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(() => { OnGuiItemChanged(); }));
}
else
{
... // update Gui Item
}
}
Run Code Online (Sandbox Code Playgroud)
但是,使用绑定源时,更改将在bindingsource内处理.所以我无法检查InvokeRequired
那么如何更新也存储在非UI线程中的绑定源中的项目?
按要求:类Person的实现和我的表单的一些代码
class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int id = 0;
private string name = null;
public int Id …Run Code Online (Sandbox Code Playgroud)