Constructor
public DocumentController(DocumentSettings config, IClipboardHandler clipboard)
| Parameter | Type | Description |
|---|---|---|
| config | DocumentSettings | Initial page layout and default text style. See DocumentSettings. |
| clipboard | IClipboardHandler | Platform clipboard implementation. Provide AvaloniaClipboardHandler in Avalonia apps. |
Avalonia Usage
In Avalonia applications,
DocumentController is created automatically by RichTextEditor during OnLoaded(). Access it via Editor.DocumentController.
Platform Callbacks
Wire these properties in your UI layer to connect the controller to your rendering and cursor systems.
Callback
Action? RequestRedraw { get; set; }
Invoke this callback when the document needs to be repainted. Set to your control's invalidation method (e.g.,
() => InvalidateVisual()).
Called internally by MoveCaret(), ScrollTo(), ScrollBy(), and OnDocumentDidChange().
Callback
Action<EditorCursor>? RequestCursorUpdate { get; set; }
Called when the cursor shape should change — for example when hovering over a resize handle.
Receives a platform-agnostic
EditorCursor value; map it to native cursor types in your UI layer.
Events
Event
event Action<NavigationInfo>? OnNavigation
Fired whenever the caret position or selection changes, and whenever the style at the caret changes.
Use this to synchronize toolbar toggle states (bold, italic, etc.) and alignment selectors.
controller.OnNavigation += (info) =>
{
// info.StyleAtCaret — IStyle at the caret
// info.SelectionInfo — alignment, list type, list level, line spacing
// info.Selection — TextRange of the current selection
UpdateToolbar(info);
};
Event
event Action<DocumentInfo>? OnContentSizeChanged
Fired when the overall document height or width changes — use this to update scrollbar ranges.
DocumentInfo carries the total Width, Height, and current ScrollOffset.
Properties
| Property | Type | Description |
|---|---|---|
| Settings | DocumentSettings | Current document configuration (read-only; update via ApplyDocumentSettings()) |
| Shortcuts | ShortcutHandler | Map custom keyboard shortcuts to editor actions |
| SelectionColor | SKColor | Background color for selected text (default: LightGray) |
| BackgroundColor | SKColor | Document page background color |
| VisibleBounds | Rectangle | Current viewport dimensions — set when the control is resized |
| HasFocus | bool | Set to true when the editor control gains keyboard focus; false when it loses focus |
| ReadOnly | bool | When true, all editing operations are suppressed |
| DocumentHeight | float | Total document height minus visible height (max scroll extent in Y) |
| PageWidth | float | Document page width in pixels |
| ScrollScale | float | Mouse wheel scroll speed multiplier (default: 20) |
Text Styling
All style methods are async Task. They apply to the current selection if one exists, or set the style at the caret (affecting subsequent typing) if no text is selected.
Method
Task ApplyBold()
Toggles bold. Font weight alternates between 400 (normal) and 700 (bold).
Method
Task ApplyItalic()
Toggles italic.
Method
Task ApplyUnderline()
Toggles underline. Cycles between
UnderlineStyle.Solid and UnderlineStyle.None.
Method
Task ApplyStrikethrough()
Toggles strikethrough. Cycles between
StrikeThroughStyle.Solid and StrikeThroughStyle.None.
Method
Task ApplySubscript()
Toggles subscript (
FontVariant.SubScript). Clears superscript if active.
Method
Task ApplySuperscript()
Toggles superscript (
FontVariant.SuperScript). Clears subscript if active.
Method
Task ApplyFontColor(SKColor color)
Sets the foreground text color of the selection or caret.
Method
Task ApplyBackgroundColor(SKColor color)
Sets the background highlight color of the selection or caret.
Method
Task ApplyFontFamily(string fontFamily)
Sets the font family by name (e.g.,
"Arial", "Times New Roman").
Method
Task ApplyFontSize(int fontSize)
Sets the font size in points.
Method
Task ApplyStyle(IStyle style)
Applies an
IStyle overlay to the selection. Only non-null properties of style are applied.
Method
void ReplaceStyle(IStyle style)
Replaces the entire style of the selection with the given style (non-async; used internally for bulk import).
Paragraph Formatting
Method
Task ApplyAlignment(TextAlignment alignment)
Sets the horizontal alignment of the paragraph containing the caret or selection.
TextAlignment values: Left, Center, Right, Justified, Auto.
Method
void SetBlockIndent(float value)
Sets the block (left) indent of the current paragraph to an absolute pixel value.
Method
void AdjustParagraphIndent(float amount)
Increases or decreases the block indent by
amount pixels. Pass positive values to indent, negative to unindent.
Method
void AdjustLineSpacing(float amount)
Adjusts the line spacing multiplier for the current paragraph. Common values: 1.0, 1.15, 1.5, 2.0.
Method
void ToggleFirstLineIndent()
Toggles first-line indent (20 px) on the current paragraph.
Lists
Method
void ToggleBulletList()
Turns bullet list on for the current paragraph, or removes the list formatting if it is already a bullet list.
Method
void ToggleNumberedList()
Same as above, for numbered (ordered) lists.
Method
void ChangeListLevel(int delta)
Changes the nesting level of the current list item. Pass
+1 to indent (increase level) or -1 to unindent.
Also triggered by Tab / Shift+Tab inside a list item.
Method
void ApplyListFormat(ListType type, int level)
Directly sets the list type and level. Primarily used by importers.
Editing & Clipboard
Method
void Insert(string text)
Inserts text at the current caret position, replacing the selection if one exists. Respects overtype mode.
Method
async Task Cut()
Copies the selection to the clipboard then deletes it.
Method
async Task<bool> Copy()
Copies the selection to the clipboard. Returns
true on success.
Method
async Task Paste()
Pastes from the clipboard. Handles both plain text and bitmap images. Images are inserted as inline objects.
Method
Task Undo()
Undoes the last editing operation. Undo history is maintained by the underlying RTK document.
Method
Task Redo()
Redoes the last undone operation.
Navigation & Pointer Input
Method
Task SelectAll()
Selects the entire document content.
Method
void SelectNone()
Collapses the selection to the caret (no selection).
Method
void Click(Point point)
Handle a mouse click (primary button down). Moves the caret to the clicked position.
If an inline image is at the click point, it is auto-selected and resize handles appear.
Point must be in document (canvas) coordinates, not screen coordinates.
Method
void DragTo(Point point)
Handle mouse drag while primary button is held.
If dragging from a text area: extends the text selection.
If dragging a resize handle on a selected image: resizes the image live.
Method
void HoverAt(Point point)
Handle mouse movement with no button held. Updates the cursor shape by calling
RequestCursorUpdate
when hovering over resize handles.
Method
void PointerReleased(Point point)
Handle primary button release. Commits any in-progress image resize as an undoable operation and re-selects the image.
Method
void ScrollBy(float x, float y)
Scrolls the viewport by a delta, scaled by
ScrollScale. Used for mouse wheel events.
Method
void ScrollTo(float x, float y)
Scrolls to an absolute position. Used to synchronize external scrollbars.
Method
async Task<bool> OnKeyEvent(KeyInfo key)
Dispatches a key event through the
ShortcutHandler. Returns true if the key was consumed.
Call this from your platform key-down handler after converting native key codes to KeyInfo.
Inline Images
Method
void InsertInlineImage(SKImage image, float displayWidth, float displayHeight)
Inserts an inline image at the current caret position. The display dimensions are automatically clamped
so the image does not exceed the available content width. The image flows with the text and can be
resized interactively using resize handles after clicking on it.
// Load from file (example)
using var data = SKData.Create("photo.png");
var img = SKImage.FromEncodedData(data);
controller.InsertInlineImage(img, 400f, 300f);
Document Configuration & Rendering
Method
void ApplyDocumentSettings(DocumentSettings settings)
Updates the document's page width, margins, and background color. Triggers a re-layout.
See DocumentSettings for all configurable values.
Method
DocumentReader GetContentReader()
Returns a
DocumentReader that iterates the document's paragraphs, runs, and styles.
Use this with the Export library to save the document to HTML, RTF, or DOCX format.
Method
void Draw(SKCanvas canvas)
Renders the document to the provided Skia canvas. Called automatically by the Avalonia platform layer.
You would only call this directly if implementing a custom renderer.
Full Usage Example
// 1. Configure the document
var settings = new DocumentSettings
{
PageWidth = 800f,
DocumentBackgroundColor = SKColors.White,
DocumentMargins = new DocumentMargins(80, 80, 60, 60),
TextStyle = new Style { FontFamily = "Segoe UI", FontSize = 14 },
Alignment = TextAlignment.Left
};
// 2. Create controller (Avalonia does this for you in RichTextEditor)
var clipboard = new AvaloniaClipboardHandler(this);
var controller = new DocumentController(settings, clipboard);
// 3. Listen for selection/style changes
controller.OnNavigation += (info) =>
{
boldButton.IsChecked = info.StyleAtCaret.FontWeight == 700;
italicButton.IsChecked = info.StyleAtCaret.FontItalic == true;
};
// 4. Listen for size changes (to update scrollbars)
controller.OnContentSizeChanged += (info) =>
{
vScrollBar.Maximum = info.Height;
};
// 5. Wire redraw
controller.RequestRedraw = () => myCanvas.InvalidateVisual();
// 6. Apply formatting
await controller.ApplyBold();
await controller.ApplyFontSize(18);