odkken
odkken

Reputation: 339

Creating a combobox of checkboxes with custom class bindings

It's pretty simple, I've got a little container class for Strings and Bools:

public class Filter
        {
        public Filter(string field, bool chec = false)
        {
            Field = field;
            Checked = chec;
        }
        public String Field { get; set; }
        public bool Checked { get; set; }
    }

And I have a list of filters in another class:

public class FilterBundle
{
    public List<Filter> Fields { get; set; }
...

Now I create a FilterBundle (filterBundle1) and try to bind a combobox to its Fields property:

<ComboBox Grid.Column="1"
    ItemsSource="{Binding filterBundle1.Fields}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Field}"
                    IsChecked="{Binding Checked}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
</ComboBox>

However, the dropdown is blank and empty. Is there something I need to do in the getters of either class to allow access to Field and Check for each Filter in filterBundle1's list?

Upvotes: 2

Views: 168

Answers (1)

Khan
Khan

Reputation: 18142

Try using an ObservableCollection as your ItemSource rather than a List.

public ObservableCollection<Filter> Fields { get; set; }

You can translate your list to one easily by:

Fields = new ObservableCollection<Filter>(MyFieldList);

In general, WPF depends on collections and properties and to implement INotifyCollectionChanged INotifyPropertyChanged respectively to update the UI.

Upvotes: 2

Related Questions