Skip to content

Live Preview

Pavel edited this page Oct 21, 2026 · 12 revisions

English | Русский

A new Markdown value does not rebuild the document: the viewer matches the new document with the shown one and applies the difference as edits. Blocks that did not change, or changed in place, keep their controls, measured heights and widget state; the selection stays while its blocks exist; the visible part does not jump when the text changes above it. So the viewer fits a preview next to an editor and answers that arrive piece by piece.

Preview next to an editor

MainWindow.xaml:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <TextBox x:Name="Editor"
             AcceptsReturn="True"
             AcceptsTab="True"
             TextWrapping="Wrap"
             VerticalScrollBarVisibility="Auto"
             FontFamily="Consolas" />

    <ScrollViewer Grid.Column="1">
        <md:MarkdownViewer Markdown="{Binding Text, ElementName=Editor}" Margin="24,16" />
    </ScrollViewer>
</Grid>

The viewer gets every keystroke. Every change parses the whole text; for long documents parse it in the background — see Long text in the background. To keep the preview at the place being edited, scroll the editor and the viewer together — see Following an editor.

To edit the source right where it is drawn, without a second pane, take the editor.

A streamed answer

An answer of a model or of the network that comes in chunks goes to the viewer through MdMarkdownStream. Append takes a chunk from any thread, and the viewer gets the whole text so far in one batch at most once per Interval, however many chunks came meanwhile. The interval is 100 ms by default; zero hands the text over as soon as possible. The first chunk after a pause goes at once. The text is applied as edits, so only the tail changes. Complete finishes the stream: the rest goes to the viewer at once, and a new chunk before Reset is an error. Reset clears the viewer and starts again.

MainWindow.xaml (xmlns:md="https://github.com/porohkun/Beresta.Markdown.Wpf" on the root element):

<ScrollViewer md:StickyScroll.Edge="Bottom">
    <md:MarkdownViewer x:Name="Viewer" Margin="24,16" />
</ScrollViewer>

MainWindow.xaml.cs, a button handler (using Beresta.Markdown.Wpf.Streaming;); the chunks here are the words of a string that come from a background thread:

private async void OnAnswer(object sender, RoutedEventArgs e)
{
    const string answer = "## Answer\n\nThe viewer gets **the text so far** in batches, so a streamed answer does not flicker.";
    var stream = new MdMarkdownStream(Viewer);

    await Task.Run(async () =>
    {
        foreach (var word in answer.Split(' '))
        {
            stream.Append(word + " ");
            await Task.Delay(40);
        }

        stream.Complete();
    });
}

A scrolling with StickyScroll.Edge="Bottom" stays at the end of the answer until it is moved up — see Sticking to the edge.

Long text in the background

A text at least BackgroundParseThreshold characters long is parsed outside the interface thread, and the result lies on the document as edits in it. Changes that come while a text is being parsed collapse into one: the next parse takes the latest text. A shorter text is parsed at once; by default — 0 — every text is.

MainWindow.xaml:

<md:MarkdownViewer Markdown="{Binding Text, ElementName=Editor}" BackgroundParseThreshold="50000" />

While a long text is being parsed, the viewer shows the previous one: TextMap, the selection and SelectedMarkdown belong to it, and the new text shows up when TextMap changes. Extensions, their resolvers and handlers, and the code highlighter are then called from a background thread; if one of them throws there — say, it touches a control — the text is parsed on the interface thread again. When it parses there without errors, RenderFailed reports the exception of the background parse with IsBackground set: the extension is not ready for a background thread — see Extensions.

A text goes to the background only when every connected extension allows it: an extension with AllowsBackgroundParse returning false keeps every parse on the interface thread. Ready-made extensions with your resolver or handlers — WikiLinks, WikiEmbeds, Mentions, Shortcodes and the sets with them — allow it only when the resolver, or the object of a handler's method, is marked IMdBackgroundSafe — see Links and References and Media and Data. The code highlighter is the same: one not marked IMdBackgroundSafe keeps every parse on the interface thread — see Code Blocks.

Identity of elements

Every element of the model has a NodeId that survives a new text while the element is unchanged or changed in place. The viewer keeps controls and widget state by it. For a widget to keep its control, its extension must return the same DataTemplate instance every time.

Another document

A new text lies on the old one as edits: an element paired with an old one keeps its control, its widget state and the selection. When the viewer shows another document — the next page, another file — give it a new DocumentKey: then nothing moves over from the previous document. The key and the text may change in any order; when the key changes before the text, the new document is parsed once.

MainWindow.xaml:

<md:MarkdownViewer DocumentKey="{Binding Page.Id}" Markdown="{Binding Page.Text}" />

Beresta.Markdown.Wpf

Basics

Working with Text

Appearance

Integration

Editing

Your Own Syntax

Ready-made Extensions


По-русски

Основы

Работа с текстом

Оформление

Встраивание в приложение

Правка

Свой синтаксис

Готовые расширения

Clone this wiki locally