问题。对于表单本身的大量文本框,我对表单属性中的字段进行了数据绑定(bind)。我不仅要更改属性中的一个字段值,还要更改整个属性(重置为以前保存的默认值)。
我想做的是这样的:
((CurrencyManager)BindingContext[Row]).Refresh();
不起作用,BindingContext[Row]
是 PropertyManager
,而不是 CurrencyManager
,并且没有刷新方法。 PushData()
protected 且不可访问。我还尝试调用 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
}
更新 我将数据绑定(bind)设置为完整的数据绑定(bind)字符串,以查看设置空值默认值是否有任何效果,但没有。
txtAzimuth.DataBindings.Add(new NullableBinding("Text", Row, "Azimuth", true, DataSourceUpdateMode.OnPropertyChanged, ""));
Row
是表单本身的公共(public)属性。 ResetRow
是表单上的私有(private)属性,它被分配给表单加载时初始行的克隆并且从未更改,它用作备份。 某些属性(但不是全部)的值允许为空,并且应显示为空字符串。这就是 NullableBinding 类在幕后所做的事情
有谁能想到比删除并重新应用每个数据绑定(bind)更好的方法吗?
最佳答案
使用 Binding.ReadValue
并没有好多少可能会省去解除绑定(bind)和重新绑定(bind)的麻烦,假设您要绑定(bind)的对象保持不变:
foreach (Control c in pnlBody.Controls)
foreach (Binding b in c.DataBindings)
b.ReadValue();
另一方面,如果您要更改底层绑定(bind)对象,则这将不起作用。我建议在 Binding
和 Row
对象之间放置一个 BindingSource
,这样你只需要重新绑定(bind)绑定(bind)源,而不是全部单独绑定(bind) 50 个。通过调用 BindingSource.CancelEdit()
或通过重置数据源:
RowBindingSource.DataSource = null;
RowBindingSource.DataSource = this.Row;
关于c# - 更改数据源时更新绑定(bind)控件的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14941537/