Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a FlowDocument with custom TextElements in wpf

Tags:

wpf

I'd like to extend the functionality of the FlowDocument by creating my own derivatives of Span and Run.

Is this possible and has anyone found any examples?

like image 499
David Hollinshead Avatar asked Aug 12 '10 14:08

David Hollinshead


2 Answers

Microsoft did not expose the methods required to render a custom TextElement inside one of their document classes. If you look at the code for a Run or Span there is no actual rendering code. The rendering takes place in UIElement's built by various internal classes (like FixedTextBuilder).

From MSDN's notes on FrameworkContentElement:

FrameworkContentElement does not yet define its own rendering behavior; instantiating an actual FrameworkContentElement class instance in code or markup is possible but displays nothing in a WPF application user interface (UI). Rendering logic must be provided by classes that take FrameworkContentElement child elements as part of their content model, or in FrameworkContentElement derived classes.

All is not lost, support for rendering custom Block and Inline elements is provided through the BlockUIContainer and InlineUIContainer classes. You could then create a low level UIElement which would be hosted inside the fixed or flow document, or use higher level WPF elements.

like image 175
user7116 Avatar answered Nov 15 '22 06:11

user7116


What kind of extensibility is required? Usually when it comes to changing default behavior of any WPF control, that couldn't be changed via inheritance, we use Attached Properties.

Here is an example of Span element, that is bound to collection of items. The same trick with attached properties helps with binding Run to a text.

The answer will also depend on the FlowDocument usage context. If it's in read-only mode, BlockUIContainer and InlineUIContainer classes are your friends. But if FlowDocument is inside RichTextBox, you'll hate and curse them (problems with copy/paste, undo/redo, etc.) along with whole WPF text support infrastructure.

like image 33
Anvaka Avatar answered Nov 15 '22 07:11

Anvaka