In my previous post I talked about how to get a dynamic set of content chunked up in to batches that could then be displayed in a static grid, stacked within an items control. This works great if your dataset is evenly divisible by the number of items in your grid, but what if it’s not?
There are two pieces to the magic you’ll see today. The first is flagging a batch as “incomplete” aka “these are the stragglers”. The second is determining how to display those guys vs the nice pretty static grid that was all laid out nicely based on being full.
Part 1: Flag the straggler batches
In the previous post we had a method that chunked up our dataset in to batches. Here’s a refresher:
Now the caveat here is that the last batch returned, if the collection isn’t divisible by 13, will have < 13 items in it. This is a problem for the ensuing XAML because the indexers go to  regardless of the content; the control assumes 13 (hence why I elected to put ‘13’ in the class name). If you don’t feed it at least 13 items, boom.
So, let’s see how we could take care of this:
We’re doing some fancy footwork here; if we determine that we’re a “straggler set,” flip the sign of the size of the batch, and feed the sign of the batch size in to the ItemViewModelBatch class. That class has been changed like this:
So now we can know if this batch is a “straggler” batch (which I’ve named a bit more professional with “AsRemainder”.
Ok sweet. We’ve got our batches and we’re noting which one is made up of stragglers. Let’s handle displaying them now.
Step 2: Determine when to display the 13-item grid or the stragglers
Any ItemsControl has a nifty little property on it called ItemTemplateSelector. The purpose of this property is to specify which Template is used to display a particular item. Now, our items are all ItemViewModelBatch objects. All of which have their # of items, and whether or not they contain the stragglers. See where I’m headed?
Set the ItemTemplateSelector property of our ItemsControl to an instance of a new class, let’s call it ItemDataTemplateSelector (because I’m super original) like so:
Our new ItemDataTemplateSelector will look like this:
In the XAML you can see we set the Remainder and Standard grids to be what we want, and then we let the selector choose based on the flag we’ve set on our batch. Voila! In this example, the “Standard” grid is our 13-item user control, while the “Remainder” grid is a GridView with all our items in it (templated as you define in the XAML).