我有一个简单的 winform,其中有一个使用列表作为数据的绑定(bind)源。每当绑定(bind)源位置发生更改时,我想采取行动。读起来,看起来“positionChanged”事件就是我所需要的。但是,在我的应用程序中,我无法触发此事件。
有一个bingingNavigator,用于使用bingingSoure 进行导航,以及(用于调试)一个用于更改当前绑定(bind)源位置的按钮。
我已尝试尽可能简化此操作。我的表单代码如下所示:
public partial class Form1 : Form
{
protected List<int> data;
public Form1()
{
InitializeComponent();
data = new List<int>();
data.Add(4);
data.Add(23);
data.Add(85);
data.Add(32);
}
private void Form1_Load(object sender, EventArgs e)
{
bindingSource1 = new BindingSource();
bindingSource1.DataSource = data;
bindingNavigator1.BindingSource = this.bindingSource1;
}
private void bindingSource1_PositionChanged(object sender, EventArgs e)
{
// Debugger breakpoint here.
// Expectation is this code will be executed either when
// button is clicked, or navigator is used to change positions.
int x = 0;
}
private void button1_Click(object sender, EventArgs e)
{
bindingSource1.Position = 2;
}
}
事件处理程序是在设计器中自动生成的:
//
// bindingSource1
//
this.bindingSource1.PositionChanged += new System.EventHandler(this.bindingSource1_PositionChanged);
现在,问题是每当我运行这个时,“PositionChanged”事件就不会触发。我已经验证 bindingSource1.Position 根据导航器和按钮进行更改。但无论我做什么,该事件实际上都不会发生。我猜这在这一点上是相当愚蠢的,或者我完全误解了事件应该何时触发。
使用.NET 4.5
最佳答案
问题出在您的Form_Load
private void Form1_Load(object sender, EventArgs e)
{
// this overrides the reference you have created in the desinger.cs file
// either remove this line
bindingSource1 = new BindingSource();
// or add this line
// bindingSource1.PositionChanged += bindingSource1_PositionChanged;
bindingSource1.DataSource = data;
bindingNavigator1.BindingSource = this.bindingSource1;
}
当您创建新对象 new BindingSource()
时,它没有订阅 PositionChanged
事件。这就是为什么你永远不会到达断点的原因。
关于C# Windows 窗体 : BindingSource PositionChanged event not firing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16657309/