为什么绑定文本框不修改其关联的 属性 文本值是以编程方式设置的?

Why does a Bound Textbox not modify its associated property is the Text value is set programmatically?

我有一个包含多个文本框的 Windows 表单。我将它们绑定到数据源作为表单加载。

public partial class FormSettings : Form
{
    private readonly DbContext _context = new DbContext();

    public FormSettings()
    {
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        _context.OrderEntrySettings.Load();

        SettingsBindingSource.DataSource = _context.OrderEntrySettings.Local.ToBindingList();

        Binding saNbinding = new Binding("Text", SettingsBindingSource, "InvoiceNumber");

        InvoiceNumberTextBox.DataBindings.Add(saNbinding);

        Binding pthNbinding = new Binding("Text", SettingsBindingSource, "SalesOrderExportPath");

        PathTextBox.DataBindings.Add(pthNbinding);

    <snip>
    …   
    </snip>
}

其中一个文本框绑定到目录路径(字符串)属性。 如果我在路径文本框中输入一个新目录并点击我的保存按钮,路径保存得很好。

但是,如果我将文本框上的文本 属性 更改为 FolderBrowserDialog 对话框中的 SelectedPath,然后点击保存,文本框文本会显示我选择的目录,但实体不会被修改,也不会保存任何内容返回数据库。

作为解决方法,我设置了路径文本框文本并将上下文中的 属性 设置为 SelectedPath。

如果以编程方式设置文本值,为什么绑定文本框不修改其关联的 属性?

如果没记错的话,WinForms(可能还有 WebForms)中的数据绑定使用控件焦点的变化来检测字段中的数据何时发生变化。

在代码隐藏中修改控件的值时,通常不会更改控件焦点。因此,没有任何东西可以戳破数据绑定引擎的肋骨并提示它需要重新评估数据这一事实。

原因在这里。 Binding class has a property called DataSourceUpdateMode 有 3 个选项 - NeverOnPropertyChangedOnValidationlast 是默认值。当您以编程方式设置 Text 属性 时,没有 validating/validated 事件,因为它们仅在控件处于焦点上并且已被编辑时触发,因此绑定不会更新数据源。

话虽这么说,但您有以下选择:

(A) 不要以编程方式设置控件 属性,而是设置数据源 属性。

(B) 将绑定 DataSourceUpdateMode 更改为 OnPropertyChanged。然而,这将导致数据源 属性 在用户键入的每个字符上更新。

(C) 使用以下代码段:

yourTextBox.Text = ...;
yourTextBox.DataBindings["Text"].WriteValue();