2014-01-21 72 views
1

有沒有辦法讓null?如果我這樣做,它將它作爲0.該屬性在業務類和SQL表中可爲空。我使用了一個帶有ClearSelectionButton的Combobox,所以也許已經有一種方法可以在View中修復它。設置爲空而不是0 - int

我在查看組合框

   <telerik:RadComboBox x:Name="CommandButton" ItemsSource="{Binding Path=ColorList}" 
            SelectedValue="{Binding Path=Model.Color, Converter={StaticResource VCShortIntToInt}, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" 
            DisplayMemberPath="Text" SelectedValuePath="number" ClearSelectionButtonVisibility="Visible" ClearSelectionButtonContent="empty" /> 

我在企業級

public static PropertyInfo<short?> ColorProperty = RegisterProperty<short?>(c=>c.Color); 
    public short? Color 
    { 
     get { return GetProperty<short?>(ColorProperty); } 
     set { SetProperty<short?>(ColorProperty, value); } 
    } 

轉換

public class VCShortIntToInt : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     Int32 result = 0; 
     if (value != null && value.GetType() == typeof(Int16)) 
     { 
      result = System.Convert.ToInt32(value); 
     } 
     return result; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     Int16 result = 0; 
     if (value != null && value.GetType() == typeof(Int32)) 
     { 
      result = System.Convert.ToInt16(value); 
     } 
     return result; 
    } 
} 

回答

3

有沒有辦法轉移NULL屬性?如果我嘗試這樣,它把它作爲0

那是因爲你的轉換器,當輸入null返回0。看看你的ConvertBack方法(由我添加的註釋):

Int16 result = 0;  // result is initialized to 0 

    // Since `value` is `null`, the if branch is not taken 
    if (value != null && value.GetType() == typeof(Int32)) 
    { 
     result = System.Convert.ToInt16(value); 
    } 

    return result;   // 0 is returned. 

解決方法很簡單:只要保持返回值「可空」:

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    return (Int16?)value; 
}