简体   繁体   中英

Data Templates And List Box

In my application i have a list box with a data template on his ItemTemplate, with some text blocks and check box. I use this app to load an excel sheet, read its contents and add some itens to the list box (the objective is create a text block for description and a check box for a event).

My first idea was to use a DataGrid, but, when i'm reading the sheet, i have to create events for the check boxes (one event for each CB), but i could not do it with DataGrid. Then, i went to the list box option, using the data template in ItemTemplate. But i was stuck on the "null" problem object when using ContentPresenter (from what i read, it's because the item on the list box isn't "ready", some bug on WPF).

So, there's another way to "automate" this ? Or i have to create each text block and check box ?

Thanks ! (sorry for the bad english)

The orthodox way to implement this is to construct a view model object to represent each item you want to display. This view model would likely contain a bool property and a string property to hold your data. As you parse the excel sheet, for each entry, construct an instance of your view model, put the data in it, and then add it to a list

After you read all your excel data, you can go about implementing the presentation of your data. First, declare a DataTemplate for your view model object. In this DataTemplate, bind a checkbox to your bool and a textblock/label to your string. Next, declare a ListBox and bind your view model list instance to ListBox.ItemsSource . If you did everything correctly you should see a listbox with each row containing a checkbox and a description.

Note: if you want the user to be able to modify the data in your view model, be sure to implement INotifyPropertyChanged on your view model object and use TwoWay binding in your DataTemplate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM