【问题标题】:How do I know when the binding is setting the textbox vs the user?我如何知道绑定何时设置文本框与用户?
【发布时间】:2010-11-04 18:30:34
【问题描述】:

我有一个带有文本框的表单。我创建了一个 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 设置的,还是因为用户输入了某些内容(或粘贴了它)。我如何获得这些信息?

我尝试在创建绑定时设置一个标志,但在绑定时,文本框位于不可见的选项卡控件上。当我切换到带有相关文本框的选项卡时,该事件实际上会触发。

【问题讨论】:

    标签: c# winforms data-binding


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      您是否有理由必须使用TextChanged 事件进行用户输入?您能否考虑改用另一个事件,例如KeyPress?这完全取决于文本更改时您需要做什么。另一种选择是将 TextChanged 上的值与 DataBoundItem 进行比较。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多