Question

Got a situation where checkboxes in a UI need to be bound to a numeric parameter - effectively, certain values make the checkbox "true", otherwise it's "false".

Easiest way to do this seemed to be to use a converter:

[ValueConversion(typeof(int), typeof(bool?))]
public class TypeToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (targetType != typeof(bool?))
            throw new InvalidOperationException("The target must be a bool");

        if( (value < 3)
        {
            return true;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplmentedExpection();
    }
}

And then in the XAML:

<CheckBox IsChecked="{Binding Path=Type.TypeID, Converter={StaticResource TypeConverter}}" />

Which works like a charm when using Convert, but fails utterly when using ConvertBack because it needs to know what the numeric value was (it depends on other UI elements) before it can know what number to return - effectively it needs access to the bound object.

I assumed I could do this with a ConverterParameter, but from the looks of things you can't bind a value to this property.

Is there a way out of this mess?

EDIT: I have solved this by messing around with the original bindings, and got away with it because on uncheck all I want to do is delete the item anyway. But I'm going to leave this in place since it seems a valid issue and I'm curious about possible solutions.

Was it helpful?

Solution

Why don't you just bind to something and do the work in what you are binding, for example a viewmodel? It probably will be cleaner and faster.

Converters are nice in theory, but after building many large WPF projects, I almost never use them for reasons like above. Sure, you can get it to do what you want, but what's the point? You have much less control of how and when these conversions happen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top