考慮這個源:C# - 問題從綁定System.String要System.Nullable <Sytem.Int32>鑄造
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中的代碼進行測試和工作,但我不能解決這個問題...
請幫助。
在哪裏拋出的異常?如果您不知道,請在拋出異常時啓用Break。 – 2010-03-17 16:11:31
我這樣做對Visual Studio來捕獲異常:菜單 - >調試 - >例外,然後選中了「InvalidCastException的」。因此,該程序飛奔,當我把在text_box一些號碼在Visual Studio提出與消息的異常:「從‘System.String’到「System.Nullable'1無效施放[[System.Int32,mscorlib程序,版本= 2.0.0.0文化=中性公鑰= b77a5c561934e089]]」。「。 – 2010-03-17 17:33:50