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!
- Define a class to hold the category name (
string
) and its checked status (bool
). - Define a collection of type
ObservableCollection<T>
where T is the class you just defined in (1). - Create an
ItemsControl
in XAML and bind itsItemsSource
property to the collection from (2). - Define a
DataTemplate
in XAML in which you display aCheckBox
and aTextBlock
, bind them to the appropriate properties in your object from (1). - Don't forget to set your
ItemsControl.ItemTemplate
to theDataTemplate
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.)
精彩评论