質問

Is there a way to transfer null? If I try so, it takes it as 0. The Property is nullable in the Business-Class and in the SQL-Table. Im using a Combobox with a ClearSelectionButton so maybe there is already a way to fix it in the View.

My ComboBox in the View

                <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" />

My Property in the Business-Class

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

Converter

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;
    }
}
役に立ちましたか?

解決

Is there a way to transfer null? If I try so, it takes it as 0.

That's because your converter returns 0 when the input is null. Have a look at your ConvertBack method (comments added by me):

    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.

The solution is simple: Just keep the return value "nullable":

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    return (Int16?)value;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top