【问题标题】:DataBinding Winforms Controls onto Nullable Types Locks Up GUIDataBinding Winforms 控件到可空类型锁定 GUI
【发布时间】:2019-10-30 15:27:43
【问题描述】:

我有一个允许用户编辑对象数组的 Winforms 应用程序。通过单击DataGridView 中的一行来选择对象,并将数据绑定到各种控件。
最近,我希望该对象能够处理空值(对于还没有数据的字段)。这是使用type? 约定完成的。

private PDAFiles? pdafile;
public new PDAFiles? PDAFile
{
    get { return this.pdafile; }
    set { this.pdafile = value; }
}

一些额外的处理(通过自定义格式)允许正确读取和写入字段。但是,在控件中输入值会锁定 GUI。

在实现可为空的type? 类型之前,我的代码按预期工作。查看调试器中的变量会发现所有值都已正确读取/写入。该程序不会引发任何异常。大多数控件,包括关闭按钮,都无法交互。 DataGridView,选择要绑定的对象,可以与之交互,选择不同的对象/添加对象恢复功能。

ComboBox 控件上的数据绑定:

Binding binding = new Binding("SelectedIndex", this.current_criteria, "PDAFile", true);
binding.Format += (sender, e) =>
{
    try
    {
        e.Value = e.Value == null ? -1 : e.Value;
    }
    catch { }
};
this.signalFileBox.DataBindings.Add(binding);

删除这些行会导致问题消失。但是,由于控件不再是数据绑定的,因此它不会从对象加载现有值。单独的绑定解析用户输入。删除解析器对锁定 GUI 没有影响。

DataGridView 设置DataSource

this.selected_row_index = this.dataGridViewCriteria.CurrentCell.RowIndex;
MultiDataCollectionCriteria sources =
    new MultiDataCollectionCriteria
    (
        (from row in this.dataGridViewCriteria.SelectedRows.Cast<DataGridViewRow>() 
        select this.data_criteria_source[row.Index] as DataCollectionCriteria).ToArray()
    );
this.current_criteria.DataSource = sources;
this.criteriaPanel.Enabled = true;

这些行按预期运行;但是,如前所述,从 DataGridView 中选择一个新行会解锁 GUI。

我希望能够将控件绑定到可空类型(带格式)而不会导致 GUI 锁定。该行为与普通的DataBinding 相同,只是它可以处理type? 源。

【问题讨论】:

    标签: c# winforms data-binding nullable


    【解决方案1】:

    在这里提出了类似的问题
    Best way to databind a Winforms control to a nullable type?

    通过将绑定更改为Binding binding = new Binding("SelectedIndex", this.current_criteria, "PDAFile", true, DataSourceUpdateMode.Never, -1);解决了问题

    DataSourceUpdateMode.NeverDataSourceUpdateMode.OnPropertyChanged 相比尤为重要,因为我是通过单独的方式手动解析输入的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2013-05-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多