Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databind a nullable type in XAML\Windows 8 store app

I have a TextBox in XAML which I'm trying to databind to a nullable int. This is the code for my textbox and linked converter:

<TextBox x:Name="textArea" InputScope="Number" Text="{Binding Area, Mode=TwoWay, Converter={StaticResource NullableValueConverter}}" />

public class NullableValueConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        if (String.IsNullOrEmpty(value.ToString()))
        {
            return null;
        }

        return value;
    }
}

When every I enter a number in this textbox the databind doesn't seem to work and the datasource is always left as null. How can I get round this?

I'm using XAML & C# to design a windows store application.

Thanks in advance.

like image 735
Sun Avatar asked Dec 01 '25 08:12

Sun


1 Answers

I agree with Sacha's answer, but if you need a NullableValueConverter an improvement would be

public class NullableValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                          CultureInfo culture)
    {
        return value == null ? string.Empty : value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, 
                              CultureInfo culture)
    {
        string s = value as string;

        int result;
        if (!string.IsNullOrWhiteSpace(s) && int.TryParse(s, out result))
        {
            return result;
        }

        return null;
    }
}

Note that this was tested using WPF so the method signatures may be different from WinRT.

like image 113
Phil Avatar answered Dec 02 '25 22:12

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!