I need to get a untyped QueryableCollection from a DataContext to query it. I have the following code:
printAbleListView = (ListView) printObject.FindName("printAbleListView");
// Here I like to have something like ObservableCollection<Object>
ObservableCollection<Journal> allItems = (ObservableCollection<Journal>) printAbleListView.DataContext;
// Add the page to the page preview collection
for (int i = 0; i <= (allItems.Count()/30); i++)
{
printAbleListView.DataContext = null;
printAbleListView.DataContext = allItems.Skip(30 * i).Take(30);
document.SetPreviewPage((i + 1), printObject);
}
The goal is to print out any ListView in a Metro-Style Windows 8 app. Currently it is typed to the Journal
DataType, but I like to have it untyped so the function can be reused for every ListView, not only for the Journal
ones. Hw can i archive this?
Example:
void GeneratePreview<T>(int itemsPerPage)
{
var printAbleListView = (ListView)printObject.FindName("printAbleListView");
var allItems = (ObservableCollection<T>)printAbleListView.DataContext;
// Add the page to the page preview collection
for (int i = 0; i <= (allItems.Count()/itemsPerPage); i++)
{
printAbleListView.DataContext =
allItems.Skip(itemsPerPage * i).Take(itemsPerPage);
document.SetPreviewPage((i + 1), printObject);
}
}
For untyped access, you can actually use the fact that ObservableCollection<T>
supports non-generic ICollection
:
void GeneratePreview(int itemsPerPage)
{
var printAbleListView = (ListView)printObject.FindName("printAbleListView");
var allItems = (ICollection)printAbleListView.DataContext;
var slice = new List<object>(itemsPerPage); // cannot use ArrayList for Win8 apps
var pageNo = 1;
foreach (var item in allItems)
{
slice.Add(item);
if (slice.Count % itemsPerPage == 0)
{
// flush
printAbleListView.DataContext = slice;
document.SetPreviewPage(pageNo, printObject);
// and restart
pageNo++;
slice.Clear();
}
}
if (slice.Count != 0) // flush the rest
{
printAbleListView.DataContext = slice;
document.SetPreviewPage(pageNo, printObject);
}
// clean up
printAbleListView.DataContext = null;
}