【问题标题】:C# Windows Forms : BindingSource PositionChanged event not firing?C# Windows 窗体:BindingSource PositionChanged 事件未触发?
【发布时间】:2013-05-20 19:54:44
【问题描述】:

我有一个简单的 winform,它带有一个使用 List 作为数据的 bindingSource。每当绑定源位置发生变化时,我都想采取行动。阅读起来,我需要的是 'positionChanged' 事件。但是,在我的应用程序中,我无法触发此事件。

有一个 bindingNavigator 用于使用 bindingSoure 进行导航和(用于调试)一个更改当前绑定源位置的按钮。

我已尝试尽可能简化这一点。我的表单代码如下所示:

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;
    }
}

eventHandler 在设计器中自动生成:

        // 
        // bindingSource1
        // 
        this.bindingSource1.PositionChanged += new System.EventHandler(this.bindingSource1_PositionChanged);

现在,问题是每当我运行它时,'PositionChanged' 事件都不会触发。我已经验证了 bindingSource1.Position 基于导航器和按钮的变化。但无论我做什么,该事件都不会真正触发。我猜在这一点上这是非常愚蠢的事情,或者我完全误解了事件应该何时触发。

使用 .NET 4.5

【问题讨论】:

    标签: c# winforms bindingsource


    【解决方案1】:

    问题出在你的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。这就是为什么您永远不会遇到断点的原因。

    【讨论】:

    • 感谢 Jens 的快速回复,看来我今天早上不是很聪明。全部修复,我会尽快标记为答案。
    • @Sperry 我的荣幸 :) 这是一个诚实的错误。我愿意承认的次数更多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多