为什么在使用WriteValue更新布尔绑定时会出现格式异常?

Rac*_*hel 13 c# data-binding binding .net-3.5

我的表单上有一堆Checkbox,其Checked属性绑定到数据模型上的Boolean属性:

chk1.DataBindings.Add(new BindingValue(this, "Checked", "MyBooleanProperty1", false))
chk2.DataBindings.Add(new BindingValue(this, "Checked", "MyBooleanProperty2", false))
chk3.DataBindings.Add(new BindingValue(this, "Checked", "MyBooleanProperty3", false))
Run Code Online (Sandbox Code Playgroud)

屏幕上的所有复选框都有一个共享事件处理程序,可确保将数据绑定值正确设置为选中的值.

private void AllCheckboxes_CheckedChanged(object sender, EventArgs e)
{
    var chk = ((CheckBox)sender);

    var binding = chk.DataBindings["Checked"];
    if (binding != null)
        binding.WriteValue();
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,第一次加载此表单和绑定时,我得到一个例外:

无法将值格式化为所需类型.

System.Windows上System.Windows.Forms.Binding.PullData(Boolean reformat,Boolean force)的System.Windows.Forms.BindToObject.SetValue(Object value)中的System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component,Object value) .Forms.Binding.WriteValue()

它适用于处理事件的第一个复选框,但第二个复选框将抛出此异常.

数据源是我的数据模型的接口

public interface IMyDataModel
{
    bool MyBooleanProperty1 { get; set; }
    bool MyBooleanProperty2 { get; set; }
    bool MyBooleanProperty3 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我可以通过在事件处理程序中的.WriteValue之前设置断点来验证数据模型本身是否设置正确.我甚至可以在绑定的布尔属性的setter中放置一个断点,并且它也被正确调用.

如果我将FormattingEnabled绑定的属性设置为true,它确实解决了问题.但我想知道为什么我首先必须这样做,因为我System.Boolean将UI对象中的bool属性绑定到数据源上的属性.

在这种情况下,为什么我会得到这个例外?

Jer*_*emy 1

如果没有办法重现问题,很难确定发生了什么。

但至少我可以解释为什么设置FormattingEnabled会使异常消失:

http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/Binding.cs,853

WriteDataPullData使用reformat = true和进行呼叫force = true

从您的调用堆栈来看,您似乎必须将其放入此块中:

            // Put the value into the data model
            if (!parseFailed) {
                this.bindToObject.SetValue(parsedValue);
            }
Run Code Online (Sandbox Code Playgroud)

紧接着,异常将被重新抛出,除非 FormattingEnabled = true。因此,FormattingEnabled在这里设置隐藏了问题,因为它似乎Binding假设您将自己处理迄今为止发现的任何格式/解析问题。

至于为什么首先抛出异常......我不知道。看这里没有什么明显的:

http://referencesource.microsoft.com/#system/compmod/system/componentmodel/ReflectPropertyDescriptor.cs,1138

如果您找到一种无需自定义类即可添加数据绑定的方法,我很想知道您的问题是否仍然存在BindingValue。我也很好奇你是否有任何听众连接到BindingValue.