Entity
Entity

Reputation: 8202

Bind List of strings to UI as Checkboxes?

I have a List<String> in a custom user control. Whenever the List<String> is modified, I want the custom user control to have checkboxes for every item in the List<String>. My original idea (being used to Java) was to just add the checkboxes and remove them directly.

But... I know C# can do better than that. Is there some way I can "bind" the strings to the UI so they show up as checkboxes? (or any other method that works?)

Upvotes: 3

Views: 3244

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292405

You can do that easily by binding an ItemsControl to the list of strings:

<ItemsControl ItemsSource="{Binding Strings}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

However that's not very useful, because you have no easy way to access the state of the CheckBox... A better option would be to wrap the string in a class that also exposes a bool property:

public class CheckableItem<T> : INotifyPropertyChanged
{
    public CheckableItem(T value)
    {
        _value = value;
    }

    private T _value;
    public T Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged("Value");
        }
    }

    private bool _isChecked;
    public bool IsChecked
    {
        get { return _isChecked; }
        set
        {
            _isChecked = value;
            OnPropertyChanged("IsChecked");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

You can then expose a list of CheckableItem<string> instead of a list of strings, and change the XAML as follows:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Value}" IsChecked="{Binding IsChecked}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

If you need to test if the CheckBox is checked, just test the IsChecked property in the CheckableItem<T> class.

If you need the CheckBox to have 3 states (checked/unchecked/indeterminate), just declare IsChecked as bool? instead of bool.

Upvotes: 9

Related Questions