考虑以下源代码:
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内部的代码经过测试可以正常工作,但我无法解决这个问题...请帮忙。