简体   繁体   中英

Binding WPF CheckBox.IsChecked to a list

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

在此处输入图片说明

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:

在此处输入图片说明

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

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;
}

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