John Doe
John Doe

Reputation: 137

Binding WPF CheckBox.IsChecked to a list

Let's say I have several CheckBoxes and in ViewModel I have a List of strings.

enter image description here

public List<string> Checks { get; set; }

My goal is to bind my checkboxes to the list in such a way, that when Checkbox 1 gets checked "Check 1" will be added to the List, and when it gets unchecked "Check 1" will be removed and so on for each CheckBox.

I tried to do this with ValueConverter:

public class CheckBoxToListConverter : IValueConverter
{
    List<string> bound;
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bound = value as List<string>;

        if (bound.Contains(parameter.ToString()))
            return true;
        else
            return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool isChecked = (bool)value;

        if (isChecked)
        {
            bound.Add(parameter.ToString());
            return true;
        }
        else
        {
            bound.Remove(parameter.ToString());
            return false;
        }
    }
}

And then I did following bindings to my CheckBoxes:

<CheckBox Content="Check 1" IsChecked="{Binding Checks, Converter={StaticResource MyConverter}, ConverterParameter='Check 1'}" />
<CheckBox Content="Check 2" IsChecked="{Binding Checks, Converter={StaticResource MyConverter}, ConverterParameter='Check 2'}" />
<CheckBox Content="Check 3" IsChecked="{Binding Checks, Converter={StaticResource MyConverter}, ConverterParameter='Check 3'}" />
<CheckBox Content="Check 4" IsChecked="{Binding Checks, Converter={StaticResource MyConverter}, ConverterParameter='Check 4'}" />

This actually works the parameters get added and removed from the list accordingly. But when I Check/Uncheck the CheckBoxes they get red border around them, which most definitely indicates something is not right:

enter image description here

What is causing this error and how can I achieve this task the correct way?

Upvotes: 0

Views: 1142

Answers (1)

ASh
ASh

Reputation: 35720

Target property (ChechBox.IsChecked) has bool? type. Source property (Checks) has List<string> type.

Convert method of converter returns bool, which is compatible with IsChecked.

ConvertBack should return List<string>:

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    bool isChecked = (bool)value;

    if (isChecked)
    {
        bound.Add(parameter.ToString());
    }
    else
    {
        bound.Remove(parameter.ToString());
    }
    return bound;
}

Upvotes: 1

Related Questions