WPF ComboBox doesn't bind correctly - Binding to Nullable Ints

If you have been working with WPF and have had issues with your ComboBox or any list control binding then you can stop pulling your hair out.  The problem occurs when you try to bind the SelectedValue property of the control to a Nullable Int (int?).  I am currently working with Microsoft to resolve the root problem, but here is a work around for now:

Create an IValueConveter:

public class NullIntToNegOneConverter : IValueConverter

{                    

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

        if (value == null)

        {

            return -1;

        }

        else

        {

            return value;

        }

    }

 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

        int i;

        if (int.TryParse(value.ToString(), out i))

        {

            if (i == -1)

            {

                return null;

            }

            else

            {

                return value;

            }

        }

        else

        {

            return value;

        }

    }

 

} 

Add a, -1 value to the list that your control is bound to:

Person nullPerson = new Person();
nullPerson.Id = -1;
nullPerson.Name = "John Doe";
people.Insert(0, nullPerson); 

Bind to the Selected Value using the Converter:

<ComboBox ItemsSource="{Binding Source= {x:Static Application.Current},Path=People}"

    SelectedValuePath="Id" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="False"

    Margin="3,3,3,3" HorizontalAlignment="Right" FontSize="18"

    SelectedValue="{Binding Path=PersonId, UpdateSourceTrigger=Explicit, Converter={StaticResource    NullIntToNegOneConverter } }"/> 

You should be all set. If your id is null then you get the -1 value that you inserted in the list because the convert converts the null value to -1. However, when you go to save it to the database, the convert also converts the -1 back to a null value, so you won't have any -1 values in your database. 

Up Next
    Ebook Download
    View all
    Learn
    View all