2010-11-04 18 views
1

我有一個帶有文本框的窗體。我創建一個BindingSource對象,將我的DomainObject連接到它,然後將BindingSource綁定到一個TextBox。代碼看起來類似於此:如何知道綁定設置文本框與用戶的時間?

private BindingSource bndSource = new BindingSource(); 

private void Form1_Load(object sender, EventArgs e) { 
    bndProposal.DataSource = new DomainObject() { ClientCode = "123", EdiCode = "456" }; 
    txtAgencyClientCode.DataBindings.Add("Text", bndProposal, "ClientCode", 
           false, DataSourceUpdateMode.OnPropertyChanged, null); 

} 

private void txtAgencyClientCode_TextChanged(object sender, EventArgs e) 
{ 
    Debug.WriteLine("txtAgencyClientCode_TextChanged"); 
} 

public class DomainObject 
{ 
    public string ClientCode { get; set; } 
    public string EdiCode { get; set; } 
} 

代碼工作正常。但是,我想知道TextChanged事件觸發的原因:是因爲它是由BindingSource設置的,還是因爲用戶輸入了某個東西(或粘貼了它)。我如何獲得這些信息?

我試過在創建綁定時設置了一個標誌,但在綁定時,文本框位於不可見的選項卡控件上。當我切換到帶有問題文本框的選項卡時,事件實際上會觸發。

回答

1

您可以在設置文本後訂閱事件。禁用它在設計和形式負載添加:

private void Form1_Load(object sender, EventArgs e) { 
    txtAgencyClientCode.DataBindings.Add("Text", bndProposal, "ClientCode", 
           false, DataSourceUpdateMode.OnPropertyChanged, null); 
    txtAgencyClientCode.TextChanged += new System.EventHandler(txtAgencyClientCode_TextChanged); 

} 

,如果你想,以確保您可以在每個程序文本修改之前退訂:

txtAgencyClientCode.TextChanged -= txtAgencyClientCode_TextChanged; 
1

是否有原因需要使用TextChanged事件進行用戶輸入?你能否考慮使用另一個事件,比如KeyPress?這完全取決於文本更改時需要做什麼。另一種選擇是將TextChanged上的值與DataBoundItem進行比較。

相關問題