0

我有一个带有多个控件的表单。在某些情况下,'textBoxOtherRelationship' 被禁用并且文本设置为 string.empty。但是,当我进入另一个控件并选择标签时,数据再次出现,而控件仍然处于禁用状态。

textBoxOtherRelationship.DataBindings.Add(new Binding("Text", _binder, "RelationshipNotes"));


  private void ComboBoxRelationShipSelectedValueChanged(object sender, EventArgs e)
        {
            if ((Constants.Relationship)comboBoxRelationShip.SelectedItem.DataValue == Constants.Relationship.Other)
            {
                textBoxOtherRelationship.Enabled = true;
                if (_formMode != ActionMode.ReadOnly)
                {
                    textBoxFirstName.BackColor = Color.White;
                }
            }
            else
            {
                textBoxOtherRelationship.Enabled = false;
                _model.RelationshipNotes = null;
                textBoxOtherRelationship.Text = string.Empty;
                if (_formMode != ActionMode.ReadOnly)
                {
                    textBoxFirstName.BackColor = Color.LightYellow;
                }
            }
        }
4

2 回答 2

1

嗯..所以我在这里看到这条线:

textBoxOtherRelationship.DataBindings.Add(
  new Binding("Text", _binder, "RelationshipNotes"));

Text这告诉我您已经在 textBoxOtherRelationship 上的属性和 datasource 上名为“RelationshipNotes”的属性之间设置了绑定_binder

伟大的。

所以,我假设双向绑定工作得很好,并且当您在 中键入内容textBoxOtherRelationship并且该控件失去焦点时,底层的 RelationshipNotes 属性也会更新,对吗?

现在,查看那里的代码,我认为当您将Text属性设置为时,底层数据源不会被更新,string.Empty因为这通常不会发生,直到文本框失去焦点并且您禁用了控件。

如果添加:

textBoxOtherRelationship.DataBindings[0].WriteValue();

将值设置string.Empty为该字符串后。空值将存储回数据源,因为数据绑定将知道有一些东西需要更新。以编程方式,它没有。

我看到你有这条线:

            textBoxOtherRelationship.Enabled = false;
            _model.RelationshipNotes = null; <<<----------------------
            textBoxOtherRelationship.Text = string.Empty;

_model.RelationshipNotes最终应该绑定到该文本框的内容是什么?

于 2012-08-22T20:38:13.120 回答
1

SelectedIndexChanged 事件直到控件失去焦点后才会提交数据绑定,因此快速修复是首先在事件中写入值:

private void ComboBoxRelationShipSelectedValueChanged(object sender, EventArgs e)
{
  if (comboBoxRelationShip.DataBindings.Count > 0) {
    comboBoxRelationShip.DataBindings[0].WriteValue();

    if ((Constants.Relationship)comboBoxRelationShip.SelectedItem.DataValue ==
                                                 Constants.Relationship.Other) {
      textBoxOtherRelationship.Enabled = true;
      if (_formMode != ActionMode.ReadOnly) {
        textBoxFirstName.BackColor = Color.White;
      }
    } else {
      textBoxOtherRelationship.Enabled = false;
      _model.RelationshipNotes = null;
      textBoxOtherRelationship.Text = string.Empty;
      if (_formMode != ActionMode.ReadOnly) {
        textBoxFirstName.BackColor = Color.LightYellow;
      }
    }
  }
}
于 2012-08-22T22:27:51.303 回答