2010-03-17 18 views
2

考慮這個源: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中的代碼進行測試和工作,但我不能解決這個問題...

請幫助。

+1

在哪裏拋出的異常?如果您不知道,請在拋出異常時啓用Break。 – 2010-03-17 16:11:31

+0

我這樣做對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

回答

1

試圖玩弄這一點,這裏是我如何解決它 - 當創建文本框的結合:

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

設置格式標誌爲「true」(這是第三個參數)。

一旦你這樣做,你不需要自定義綁定了......我在OnParse註釋掉的代碼出來,它的工作原理。我只使用一個綁定對象,而不是CustomBinding,它仍然工程:)

檢查這個博客的一些細節: http://blog.jezhumble.net/?p=3

+0

它的出現,多數民衆贊成在非常只有這樣才能綁定到一個空的,我已經知道了,我們把格式化爲真會的工作,但是我已經創建了CustomBinding只是爲了和一個nulable做我自己的鑄造,但我不能找到一種方法上班。感謝您的關注和正確解決我的問題。 – 2010-03-24 13:43:01