views:

57

answers:

1

In my application I generate CheckBoxes for each possible category (retrieved from a database) and the user can check any number that apply. I name the checkboxes "cbCategory[ID]" where ID is the ID of that category in the database.

I then need to generate some sort of collection class (as a property of my object class) to store the categoryID and a boolean value (checked/unchecked).

My question is, what would be the best type of collection class to use, and how would I go about binding it? What would the XAML and Code behind for the binding look like?

Hope this explains it well enough, thanks in advance for answers!

+4  A: 
  1. Define a class to hold the category name (string) and its checked status (bool).
  2. Define a collection of type ObservableCollection<T> where T is the class you just defined in (1).
  3. Create an ItemsControl in XAML and bind its ItemsSource property to the collection from (2).
  4. Define a DataTemplate in XAML in which you display a CheckBox and a TextBlock, bind them to the appropriate properties in your object from (1).
  5. Don't forget to set your ItemsControl.ItemTemplate to the DataTemplate from (4).

Using this way, you don't need to generate controls from code, what you do need to generate is one object per category (the object defined in (1)).

And as a side note to consider - Whenever you are generating controls manually from code - you're doing it wrong, and there's an easier way using binding, styling and templating (and sometimes more advanced features such as attached properties, etc.)

Aviad P.
"Whenever you are generating controls manually from code - you're doing it wrong" : although I tend to agree with that, it's only true if you're using a pattern like MVVM... Some people might prefer to use code-behind ;)
Thomas Levesque
Preferring to use code-behind is preferring to have your application live for only as long as you remember how you coded it.
Aviad P.
Thanks Aviad. I'm pretty inexperienced when it comes to programming, even more so with OOP so this explanation helps a lot.
Cam
I think that Aviad's assertion is really an assertion that whenever you're working in WPF and you're not using MVVM, you're doing it wrong. I'm sure there are cases where this isn't true, but I can't think of one at the moment.
Robert Rossney