gpt4 book ai didi

C# 数据绑定(bind) Windows 窗体控件不保留值,除非您离开该字段

转载 作者:可可西里 更新时间:2023-11-01 08:32:34 24 4
gpt4 key购买 nike

我在 Databound Windows Forms control does not recognize change until losing focus 中看到了答案.

但这并不能完全回答我的问题。我有完全相同的情况。在 ToolStrip_click 上,我遍历了所有控件并强制使用“WriteValue()”,但它仍然恢复为保存前的先前值。谁能建议我如何解决这个问题?我是否错误地实现了这一点?

(查看当前(非工作)解决方案的代码。)

private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
// Make sure that all items have updated databindings.
foreach (Control C in this.Controls)
{
foreach (Binding b in C.DataBindings)
{
// Help: this doesn't seem to be working.
b.WriteValue();
}
}
}

代码现在简单多了,但它是一个相当大的 hack。我很高兴知道是否有更“适当”的解决方法。

private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
// Make sure that all text fields have updated by forcing everything
// to lose focus except this lonely little label.
label44.Focus();
}

最佳答案

问题可能是您的数据绑定(bind)控件设置为在验证时更新。

您需要将每个数据绑定(bind)控件的 DataSourceUpdateMode 设置为 DataSourceUpdateMode.OnPropertyChanged。例如,数据绑定(bind)文本框:

this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", 
this.someBindingSource, "SomeProperty", true,
System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));

您还可以通过以下方式在设计器中设置数据源更新模式:

选择控件并转到属性窗口 -> (DataBindings) -> (Advanced)

-> 将下拉列表中的[数据源更新模式]设置为OnPropertyChanged。

干杯

关于C# 数据绑定(bind) Windows 窗体控件不保留值,除非您离开该字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2044435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com