Printing the TreeView in WPF using MVVM

2019-04-12 15:55发布

问题:

I have a treeView to return my text search result from text files.

<TreeView ItemsSource="{Binding FirstGeneration}"
             ...>
  <TreeView.ItemContainerStyle.../>
  <TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
      <StackPanel Orientation="Horizontal" FlowDirection="LeftToRight">
        <TextBlock Text="{Binding PreExp}" />
        <TextBlock Text="{Binding Exp}"
          FontStyle="{Binding FontStyle}"
          Foreground="{Binding Color}"  />
        <TextBlock Text="{Binding PostExp}" />
      </StackPanel>
    </HierarchicalDataTemplate>
  </TreeView.ItemTemplate>
</TreeView>

To get the result as a tree (because we get the result from a C++ project as list), we create a logical tree and display the exp in red. I separated them into three textBoxes.

The treeView is in a diffrent UserControl - and I put it into the SearchView (UC).

Now I'd like to print all the results on this tree. I prefer that the document is printed with the emphasis on the search result in red.

It looks like this.

I tried the PrintDialog.PrintVisual. The problem is that I can't reach the tree or the search expression because the ViewModel does not know the view etc.

Although I tried it in the code behaind this code below and it prints only what he sees and not the entire tree results.

PrintDialog dialog = new PrintDialog();
if (dialog.ShowDialog() != true)
  return;
dialog.PrintVisual(SearchResultTree, "The Search Result Tree");

Also I tried the option with FlowDocument:

FlowDocument doc = new FlowDocument();
foreach (SearchObjectViewModel item in tv.Items)
  doc.Blocks.Add(new Paragraph(new Run(item.PreExp+item.Exp+item.PostExp)));
pd.PrintDocument(((IDocumentPaginatorSource)doc).DocumentPaginator,exp);

10x 4 helping!

回答1:

The problem is that I can't reach the tree or the search expression because the ViewModel does not know the view etc.

When using MVVM, the interaction between the View and ViewModel should happen via INotifyPropertyChanged Interface. You could map/bind one Property to one UI element; which gets a call back on Set.

Here is one of my example on mvvm-binding-treeview-item-changed. Hope it is some use.