views:

51

answers:

1

I have a bit defined in my database 0=no, 1=yes. I have a silverlight combo with the values "Yes" and "No" in it. How can I bind my bit value to the combo?

+2  A: 

You don't state what data access machinary you are using but the typical tools will expose a bit field as a boolean property. The easiest approach would be to use a value converter.

Here is the basic idea (might need some more defensive coding):-

public class BoolToStringConverter : IValueConverter
{
    public String FalseString { get; set; }
    public String TrueString { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return FalseString;
        else
            return (bool)value ? TrueString : FalseString;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.Equals(TrueString);
    }
}

With that in your application you can now add it to a Resources property (typically the App.xaml)

<Resources>
   <local:BoolToStringConverter x:Key="CvtYesNo" FalseString="No" TrueString="Yes" />
</Resources>

Now you would create your combobox like this:-

<ComboBox SelectedItem="{Binding YourBitField, Converter={StaticResource CvtYesNo}, Mode=TwoWay}">
   <sys:String>Yes<sys:String>
   <sys:String>No<sys:String>
</CombBox>
AnthonyWJones
I'm using Silverlight 3 with Linq2Sql. Thanks for the input. Let me dig into that.
Scott