I know that the wpf-documentviewer supports the searching in the documents, if the document is a xpsdocument. The search only highlights one hit after the other.
Is it possible to highlight all hits through the search-box?
I have the following code to create and set the document of a DocumentViewer-Control:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
FixedDocument fixedDocument = CreateTestDocument();
this.documentViewer.Document = BuildFixedDocumentSequence(fixedDocument);
}
private static FixedDocumentSequence BuildFixedDocumentSequence(FixedDocument fixedDocument)
{
MemoryStream ms = new MemoryStream();
Uri documentUri = new Uri("pack://document.xps");
Package p = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
PackageStore.AddPackage(documentUri, p);
XpsDocument xpsDocument = new XpsDocument(p, CompressionOption.NotCompressed, documentUri.AbsoluteUri);
XpsDocumentWriter dw = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
dw.Write(fixedDocument);
FixedDocumentSequence fixedDocumentSequence = xpsDocument.GetFixedDocumentSequence();
if (fixedDocumentSequence == null)
return null;
return fixedDocumentSequence;
}
public FixedDocument CreateTestDocument()
{
FixedDocument document = new FixedDocument();
PrintDialog printDialog = new PrintDialog();
document.DocumentPaginator.PageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);
AddPage(document, "This is the first page");
AddPage(document, "This is not the first page");
AddPage(document, "This is the third page");
return document;
}
private void AddPage(FixedDocument document, string content)
{
FixedPage page = new FixedPage
{
Width = document.DocumentPaginator.PageSize.Width,
Height = document.DocumentPaginator.PageSize.Height
};
TextBlock pageText = new TextBlock
{
Text = content,
FontSize = 40,
Margin = new Thickness(96)
};
page.Children.Add(pageText);
PageContent pageContent = new PageContent();
((IAddChild)pageContent).AddChild(page);
document.Pages.Add(pageContent);
}
}
The xaml-code consists just of the documentviewer. Now if i type in "page" into the search-box of the documentviewer and press return, the word "page" on the first page is highlighted. Through another time pressing the return-key the word "page" on the second page is highlighted.
What I want to achieve is that by pressing return for the first time, all words "page" are highlighted.
There is no easy way of doing this, that I could find. With a lot of trial and error, but mainly reflection (pun intended;), this can be done - I was still quite amazed when it actually worked.
I subclassed the DocumentViewer, and went from there. The http://reflector.webtropy.com site came in very handy, wouldn't have gotten anywhere without the source code.
The code behind didn't change, take it from the question post.
Usage:
MyDocumentViewer: