开发者

C# WPF Databinding to Unkown Amount of Checkboxes

开发者 https://www.devze.com 2022-12-19 17:06 出处:网络
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

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!


  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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号