Daniel Palme

Daniel Palme

.NET Softwareentwickler aus Augsburg/München.

Blog > WPF - Search and highlight text in DocumentViewer programmatically

WPF - Search and highlight text in DocumentViewer programmatically

The DocumentViewer is a great control for showing XPS documents in a WPF application. You can zoom and search the document, but the control does not provide a public API for its Find functionality. Microsoft is going to fix this in a future release, until then you can use the following workaround.

The DocumentViewer uses a template which contains a ContentControl named 'PART_FindToolBarHost'.
You can access it by using the following code:

object toolbar = documentViewer.Template.FindName("PART_FindToolBarHost", documentViewer);

The Content property of the ContentControl is an instance of the MS.Internal.Documents.FindToolBar class, which is a control from PresentationUI.dll. But since this class is not public you cannot cast it and access its properties directly. Therefore you have to use reflection to set the desired search term.

The FindToolBar control contains a TextBox with the name 'FindTextBox'. You have to set its Text property:

// Set Text
FieldInfo findTextBoxFieldInfo = findToolbar.GetType().GetField("FindTextBox", BindingFlags.NonPublic | BindingFlags.Instance);
TextBox findTextBox = (TextBox)findTextBoxFieldInfo.GetValue(findToolbar);
findTextBox.Text = "Lorem";

// Raise ClickEvent for Highlighting
FieldInfo findNextButtonFieldInfo = findToolbar.GetType().GetField("FindNextButton", BindingFlags.NonPublic | BindingFlags.Instance);
Button findNextButton = (Button)findNextButtonFieldInfo.GetValue(findToolbar);
findNextButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

My demo project looks like this:

DocumentViewer

Downloads

DocumentViewerDemo.zip


RSS Feed abonnieren

Tags: .NET, C#, WPF
 

Verwandte Beiträge

 

Neuer Kommentar

:

:

:

:

 

Kommentare

#1
Kenny

Kenny

05.08.2010

Excelent post,

Very useful and good post.

But now the question is, how to change the control style (findtoolbox)?

May Be programatically... I will try this.

Grettings
 
#2
Kenny

Kenny

05.08.2010

Yes, its a normal visual element, but it's private. I don´t understand why it's so closed.

Microsft should set to public this element.

DocumentViewver XPSV = new DocumentViewver();
ContentControl content = (ContentControl)XPSV.Template.FindName("PART_FindToolBarHost", XPSV);

ToolBar findToolbar = (ToolBar)content.Content;
findToolbar.Style = (Style)this.Resources["MyStyle"];

Treating it as Toolbar Control the Find Box don't change. The Style is a Toolbar style.

Grettings
 
#3
Gokul

Gokul

18.09.2010

Hi There,
Could you please let me know how can I add a few other controls along with the search toolbar.

Appreciate your help.
Thanks,
Gokul
 
#4
Daniel

Daniel

19.09.2010

@Gokul:
I'm sorry but I did don't find a solution to add controls at runtime.