Let me prefix this question by stating that I'm very new to both C# and WPF.
I'm trying to connect a collection of Boolean
values to a container containing 6 checkboxes, and have the state of these values stored when a button is pressed. I'm assuming there is an easy way to do this, since binding checkboxes to a collection of seems a very natural thing to do, but all the solutions I have seen so far have seemed overly complicated (example: http://merill.net/2009/10/wpf-checked-listbox/).
I create the checkboxes by modifying the data template of a ListBox
and set the ItemsSource
of the ListBox
to the ObservableCollection
, but my problem is that I don't know what to bind the IsChecked
to, since I'm trying to bind it to the actual object in the collection and not a property of the object.
By the link that you provided, you could also use INotifyPropertyChanged extension to your CheckedListItem class, but thats if you dont want use ObservableCollection. It would be something like this:
Your listbox should be something like this:
In your code behind you should initialize the ObservableCollection just once, because every change made into it will result into an UI update.
Now every change made into MyList, such as Add(), Remove(), Etc. Will affect your UI.
Use
IsChecked="{Binding}"
to bind the item of the collection directly.However it is not possible to do bind to source with this method. Because the binding on the
IsChecked
property of theCheckBox
doesn't the index of the item of the binding. So, it can't change the collection but only the item of the collection.Update
To get around that limitation, you can create a wrapper to the Boolean value:
Here is an exemple of usage:
And in the XAML:
In the
ItemTemplate
you may writeor
which binds directly to the item object, i.e. the
bool
value from the collection.Note however that in either case the bound values in the collection will not be replaced when a CheckBox is checked or unchecked. In order to immediately update the collection when a CheckBox is clicked, your collection would have to contain objects with a boolean property to which
IsChecked
is bound.In your case this could be as simple as the following (as your question sounds like you don't need property change notifications):
The binding would now look like this:
The collection would now be an
ObservableCollection<BooleanHelper>
and you would perhaps add items like this: