简体   繁体   中英

In C# can I change a IValueConverter for 2 values and a NULL?

At present I have 2 radio buttons on my form for Male and Female. These are bound to my database where IsMale is either a 1 for male or 0 for female.

I then use a NegativeBooleanConverter to switch between the two. My xaml looks like this:

 <RadioButton Content="Male" Name="rbMale" IsChecked="{Binding Person.IsMale, Mode=TwoWay}" />
 <RadioButton Content="Female" Name="rbFelmale" IsChecked="{Binding Person.IsMale, Converter={StaticResource NegativeBooleanConverter}}" />

My NegativeBooleanConverter looks like this:

 public class NegativeBooleanConverter : IValueConverter
{
    public object Convert(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        return !(bool)value;
    }

    public object ConvertBack(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        return !(bool)value;
    }
}

This all works great no problems!!

I have now uploaded more data into the database where IsMale is NULL as in it it unknown at the moment.

My question is is it possible to change the converter so that if the value is NULL neither radio button is selected???? If not what is the best way to achieve what I'm after?

I think this is the Convert function you're looking to put in NegativeBooleanConverter : (also a similar ConvertBack function)

var b = value as bool?;
if (b.HasValue)
    return !b.Value;
else
    return false;

If false is too specific, you could have the parameter be the "default" value, which would be returned instead.

If the IsChecked on the Male button being null is causing a problem, you could make another converter that would return ((bool?)value).GetValueOrDefault(); .

ConvertBack might be an issue, since you're essentially consolidating "male" and "unknown" into "not checked". As long as it's not too overzealous in calling that and saving the state back to IsMale , you should be ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM