【问题标题】:Better way to update bound controls when changing the datasource更改数据源时更新绑定控件的更好方法
【发布时间】:2013-02-03 04:37:27
【问题描述】:

问题。对于表单本身的大量文本框,我对表单上的属性中的字段进行了数据绑定。我不仅要更改属性中的字段值,还要更改整个属性(重置为以前保存的默认值)。

我想做的是这样的:

((CurrencyManager)BindingContext[Row]).Refresh();

不起作用,BindingContext[Row]PropertyManager,而不是 CurrencyManager,并且没有刷新方法。 PushData() 受保护且不可访问。我还尝试调用this.Refresh(),并在每个控件上单独尝试调用c.Refresh...现在呢?

这是我目前使用的代码:

private void btnReset_ButtonClicked(object sender, EventArgs e)
{
    Row = ResetRow.Clone();//use clone to break the reference, dont want to be updating the ResetRow when Row fields change.

    foreach (Control c in pnlBody.Controls)
        if (c.DataBindings.Count > 0)
            c.DataBindings.Clear();

    DataBindandSet();//re-apply all the databindings (50)
}

//just a sample of the databinding function itself
private void DataBindandSet()
{
    txtAzimuth.DataBindings.Add(new NullableBinding("Text", Row, "Azimuth", true));
    txtBHTemp.DataBindings.Add(new NullableBinding("Text", Row, "BHTemp", true));
    //repeat 48 more times
}

更新 我将数据绑定设置为完整的数据绑定字符串,看看设置空值默认值是否有任何效果,它没有。

txtAzimuth.DataBindings.Add(new NullableBinding("Text", Row, "Azimuth", true, DataSourceUpdateMode.OnPropertyChanged, ""));

Row 是表单本身的公共属性。 ResetRow 是表单上的私有属性,它分配给表单加载上初始行的克隆并且从未更改,它用作备份。 某些属性(但不是全部)的值允许为空,并且应该显示为空字符串。这就是 NullableBinding 类在幕后所做的事情

谁能想到比删除并重新应用每一个数据绑定更好的方法?

【问题讨论】:

    标签: c# winforms data-binding


    【解决方案1】:

    这并没有好多少,使用Binding.ReadValue 可能会省去解除绑定和重新绑定的麻烦,假设您要绑定的对象保持不变

    foreach (Control c in pnlBody.Controls)
        foreach (Binding b in c.DataBindings)
            b.ReadValue();
    

    另一方面,如果您正在更改底层绑定对象,这将不起作用。我建议在Bindings 和Row 对象之间放置一个BindingSource,这样您只需重新绑定绑定源,而不是单独绑定所有50 个绑定。通过调用BindingSource.CancelEdit() 或重置数据源:

    RowBindingSource.DataSource = null;
    RowBindingSource.DataSource = this.Row;
    

    【讨论】:

    • 我不知道为什么,因为这在纸上看起来很棒......但它没有更新文本框。好主意,而且比清除和重新绑定所有内容更有效,即使只是一点点。
    • @Nevyn 只是一个想法,但文本框是pnlBody 的直接子级吗?
    • 是的,所有绑定的控件都在 pnlBody 里面。表单本身也有 pnlHeader 和一些按钮和侧面板。这也是我检查c.Databindings.Count 的原因,因为文本框旁边有一些我并不真正关心的标签。
    • @Nevyn 重新阅读您的问题我知道您正在更改Row 指向的对象?如果是这样,我认为绑定仍然保留对旧对象的引用,这就是为什么这不起作用。我会尝试在绑定和Row 对象之间放置一个BindingSource
    • 似乎仍然不起作用。试过BindingSource.CurrencyManager.Refresh()BindingSource.ResetBindings()。拒绝更新文本框中的数据。
    【解决方案2】:

    试试这个:TableAdapter.Fill(dataTable)

    我的例子:this.bankingaccountTableAdapter.Fill(this.bankDataSet.bankingaccount);

    【讨论】:

    • 因为每个人总是将他们的表单绑定到DataTables。我的朋友,这些已经成为历史了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2011-03-31
    相关资源
    最近更新 更多