C# - 在绑定</sytem.int32>中从System.String转换为System.Nullable <sytem.int32>的问题

时间:2010-03-17 16:01:07

标签: c# binding casting

考虑这个来源:

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;
}

当数据输入到tex_box时,控制台中显示一条消息:“mscorlib.dll中出现'System.InvalidCastException'类型的第一次机会异常”并且永远不会达到绑定完成。 OnParse中的代码经过测试并正常工作,但我无法解决此问题......

请帮忙。

1 个答案:

答案 0 :(得分:1)

试图解决这个问题,这就是我解决它的方法 - 在文本框中创建绑定时:

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

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

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

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