2013-05-20 48 views
2

我有一個使用List作爲數據的bindingSource的簡單winform。我希望在綁定源位置發生變化時採取行動。閱讀起來,它看起來像'positionChanged'事件是我需要的。但是,在我的應用程序中,我無法啓動此事件。C#Windows窗體: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; 
    } 
} 

的事件處理程序在設計自動生成:

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

現在,麻煩的是,每當我跑這一點,「PositionChanged」事件就不會被觸發。我已經驗證了bindingSource1.Position基於導航器和按鈕進行了更改。但無論我做什麼,事件都不會實際發生。我猜這在這一點上是非常愚蠢的,或者我完全誤解了事件應該發生的時間。

使用.NET 4.5

回答

3

的問題是在你的

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認購。這就是爲什麼你從不打你的斷點。

+0

感謝您的快速回復Jens,看起來我今天早上不是非常光明。所有固定的,我會馬上標記爲答案。 – Sperry

+0

@Sperry我的榮幸:)這是一個誠實的錯誤。我更多的時間是我自己承認的。 –

相關問題