C#中数据绑定过程中从System.String到System.Nullable<Sytem.Int32>的转换问题

3

考虑以下源代码:

public partial class FormTest : Form
{
    private Test test { get; set; }

    public FormTest()
    {
        this.InitializeComponent();

        this.test = new Test();
        this.text_box.DataBindings.Add(new CustomBinding("Text", this.test, "some_int", false, DataSourceUpdateMode.OnPropertyChanged));
    }
}

class CustomBinding : Binding
{
    protected override void OnBindingComplete(BindingCompleteEventArgs e)
    {
        base.OnBindingComplete(e);

        MessageBox.Show("Yes!");
    }

    protected override void OnParse(ConvertEventArgs cevent)
    {
        Type new_type = cevent.DesiredType;
        Object new_value = cevent.Value;

        if (new_type.IsGenericType && new_type.GetGenericTypeDefinition() == typeof(Nullable<>))
            if (!new_value.GetType().IsValueType)
                new_type = new_type.GetGenericArguments()[0];
            else
                new_value = new_type.GetConstructor(new Type[] { new_value.GetType() }).Invoke(new Object[] { new_value });

        base.OnParse(new ConvertEventArgs(new_value, new_type));
    }

    public CustomBinding(String property_name, Object data_source, String data_member, Boolean formatting, DataSourceUpdateMode update_mode)
        : base(property_name, data_source, data_member, formatting, update_mode) { }
}

class Test : INotifyPropertyChanged
{
    private Int32? _some_int;

    public Int32? some_int
    { 
        get
        {
            return this._some_int;
        }
        set
        {
            this._some_int = value;

            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs("some_int"));
        }
    }                

    public event PropertyChangedEventHandler PropertyChanged;
}

当数据被输入到文本框时,控制台会显示一条消息:“mscorlib.dll中发生了类型为'System.InvalidCastException'的第一次机会异常”,并且绑定完成永远不会被执行。OnParse内部的代码经过测试可以正常工作,但我无法解决这个问题...请帮忙。

1
异常抛出在哪里?如果您不知道,请启用“异常抛出时中断”。 - Igby Largeman
我在Visual Studio上进行了以下操作以捕获异常:菜单->调试->异常,然后选中“InvalidCastException”。因此,在程序运行时,当我在文本框中输入一些数字时,Visual Studio会引发异常,并显示消息:“从'System.String'到'System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'的无效转换。”。 - Leonardo Justino
1个回答

2

我尝试着对此进行了一些操作,以下是我的解决方案 - 在文本框上创建绑定时:

this.text_box.DataBindings.Add(new CustomBinding("Text", this.test, "some_int", false, DataSourceUpdateMode.OnPropertyChanged));

将格式化标志设置为“true”(它是第三个参数)。

一旦您这样做了,您就不再需要自定义绑定了......我在OnParse中注释了代码,并且它可以工作。我只使用一个绑定对象而不是CustomBinding,它仍然有效:)

查看此博客获取详细信息: http://blog.jezhumble.net/?p=3


似乎这是绑定到可空类型的唯一方法,我已经知道设置格式为true可以工作,但是我创建了CustomBinding来进行自己的从可空类型到非空类型的转换,但是我找不到解决方法。感谢您的关注和正确解决我的问题的答案。 - Leonardo Justino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接