0

我需要从 DataContext 获取无类型的 QueryableCollection 来查询它。我有以下代码:

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);
}

目标是打印出 Metro 风格 Windows 8 应用程序中的任何 ListView。目前它被输入到JournalDataType,但我喜欢让它不被输入,这样这个函数就可以被每个 ListView 重用,而不仅仅是Journal那些。我可以存档吗?

4

1 回答 1

3

例子:

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);
    }
}

对于无类型访问,您实际上可以使用ObservableCollection<T>支持 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;
}
于 2013-03-03T14:05:03.427 回答