WPF binding Enum list (or similar) to list of checkboxes

binding, c#, data-binding, mvvm, wpf

Solution

Assuming you want to bind to all possible values of your enum, you can do it with an ObjectDataProvider. Declare this in your resources (`Window.Resources` or `App.Resources` etc.):

    <ObjectDataProvider x:Key="enumValues" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:TestEnum"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>

This basically represents a call to `Enum.GetValues(typeof(TestEnum))` and exposes it as a data source. Note: You need to declare the namespaces `sys` and `local` before, where `sys` is `clr-namespace:System;assembly=mscorlib` and `local` is the namespace of your enum.

Once you have that, you can use that ObjectDataProvider as a Binding source just like anything else, for example:

<ListBox ItemsSource="{Binding Source={StaticResource enumValues}}"/>

The non-declarative way of doing this is just assigning that in code:

someListBox.ItemsSource = Enum.GetValues(typeof(TestEnum));

For binding the selected items, unfortunately the SelectedItems property cannot be set from Xaml, but you can use the SelectionChanged event:

<ListBox Name="lb" ItemsSource="{Binding Source={StaticResource enumValues}}" SelectionMode="Multiple" SelectionChanged="lb_SelectionChanged"></ListBox>

and then set the property on your ViewModel (or whatever you use) in the event:

private void lb_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    viewModel.SelectedValues = lb.SelectedItems.OfType<TestEnum>().ToList();
}

Problem

I would like to bind a checkbox list to a collection of enum values in WPF. The enum is not [Flags]. Context: It is for filtering a datagrid, in which each item has a instance of my enum. It doesn't necessarily need to bind to an List, a fixed size collection of would work as well.

Original source