WinForms:如果添加带有 "Changed" 后缀的事件,为什么数据绑定会中断?

WinForms: Why does databinding break if adding an event with "Changed" suffix?

有一个模型 class,其中 public DataTable 变量名为“RelatedPrograms”。它通过数据绑定用作 UserControl class 中 DataGridView 控件的源:

dataGridView.DataBindings.Add("DataSource", Model, nameof(Model.RelatedPrograms), false, DataSourceUpdateMode.OnPropertyChanged);

现在,如果我向模型引入一个名为“RelatedProgramsChanged”的新事件字段 class

public event EventHandler<EventArgs> RelatedProgramsChanged;

数据绑定停止工作,并且 DataGridView 不会用 DataTable 中的数据刷新。但是列显示正确。是什么原因造成的?只要变量不以 -Changed 结尾且未定义为事件,一切都可以正常工作。

如果您正在定义 RelatedProgramsChanged,您还应该在 属性 值更改时触发该事件。您没有显示足够的代码来查明您的实现中的失败点。

PropertyNameChanged 事件是在引入 INotifyPropertyChanged Interface. For more information see: Property-Changed Events.

之前发出更改信号的方式

来自 INotifyPropertyChanged 的​​ Remarks 部分:

For change notification to occur in a binding between a bound client and a data source, your bound type should either:

  • Implement the INotifyPropertyChanged interface (preferred).

  • Provide a change event for each property of the bound type.

Do not do both.

此事件连同 ShouldSerializePropertyName 和 ResetPropertyName(参见:Defining Default Values with the ShouldSerialize and Reset Methods) methods are retrieved by the property descriptor used by the WinForm binding mechanism. You can inspect the propery descriptor code at ReflectPropertyDescriptor 并阅读评论以了解更多信息.