C# Windows 窗体 : BindingSource PositionChanged event not firing?

标签 c# winforms bindingsource

我有一个简单的 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/

相关文章:

c# - DataGridView 更新数据源受 ProcessDataGridViewKey 阻碍?

c# - 配置弹性设置 Entity Framework 6.02

C# - 接口(interface)说明

c# - 为什么物体永远不动?

c# - Winforms 控件结合了 SplitContainer 和 TableLayoutPanel 的优点

sorting - 使用 bindingsource 在正确位置向用户排序的 wingrid 添加新行

javascript - ASP 找到包含 0 个元素的下拉列表,但元素就在那里

c# - 从函数更新另一个窗口中的 ProgressBar?

.net - 如何在 RichTextBox 中创建上下文菜单

c# - 在 C# 中使用 List<> 作为 BindingSource