设置Null但不是0 - int

时间:2014-01-21 07:47:44

标签: sql-server wpf mvvm telerik csla

有没有办法转移null?如果我这样做,则将其视为0.该属性在Business-Class和SQL-Table中可以为空。我使用带有ClearSelectionButton的Combobox,所以可能已经有办法在View中修复它。

视图中的我的ComboBox

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

1 个答案:

答案 0 :(得分:3)

  

有没有办法转移null?如果我这样做,则将其视为0。

这是因为当输入为0时,转换器会返回null。看看你的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;
}