Skip to content

Copying

Pavel edited this page Oct 19, 2026 · 7 revisions

English | Русский

Ctrl+C, the context menu and Copy() put the selection on the clipboard in three formats at once, and the application you paste into takes the one it understands.

Format What is in it Who takes it
DataFormats.UnicodeText plain text, as on the screen Notepad, terminals, plain text fields
MdDataFormats.Markdown (text/markdown) the selection written as Markdown, UTF-8 bytes your applications
DataFormats.Html the selection as HTML Word, mail, rich text editors

The Markdown is written anew from the document model. A piece of one line keeps its inline formatting and links with their titles; several blocks also keep headings, lists, quotes, code blocks and tables. Reference links become inline ones, and _italic_ becomes *italic*. A widget selected as a whole is written as its source text.

The HTML is made from this Markdown by the same Markdig pipeline as the document, extensions included: the syntax of an extension gets the HTML of its Markdig extension, and without one stays source text. The HTML repeats the screen: an image that ImagePolicy did not let through, and every image when ImageLoader is {x:Null}, goes as its alt text; the other images get absolute addresses, resolved against BaseUri, and an absolute BaseUri goes into the HTML as the address of its source.

Your code that pastes (using System.IO; using System.Text; using Beresta.Markdown.Wpf.Selection;):

if (Clipboard.GetData(MdDataFormats.Markdown) is MemoryStream stream)
{
    var markdown = Encoding.UTF8.GetString(stream.ToArray());
}

Copy as Markdown

Ctrl+Shift+C, the menu item «Copy as Markdown» and CopyMarkdown() put the Markdown of the selection as plain text: paste it into any text field, and the formatting survives as markup. The command behind them is MarkdownViewer.CopyMarkdownCommand, so your own button can use it too.

A window or a user control:

<Button Content="Copy as Markdown"
        Command="{x:Static md:MarkdownViewer.CopyMarkdownCommand}"
        CommandTarget="{Binding ElementName=Viewer}" />

Without the clipboard, the same texts are in SelectedText and SelectedMarkdown.

Changing what is copied

Before writing to the clipboard the viewer raises the standard DataObject.Copying event. A handler on the viewer or on any of its ancestors gets the data with all three formats: it can add its own format or cancel the copying. The copy button of a code block raises the same event.

MainWindow.xaml.cs, in the constructor after InitializeComponent():

DataObject.AddCopyingHandler(Viewer, (_, e) =>
{
    if (IsDocumentProtected)
    {
        e.CancelCommand();
        return;
    }

    e.DataObject.SetData("YourApp.DocumentId", DocumentId);
});

IsDocumentProtected and DocumentId stand for your own state.

Giving Ctrl+C to the application

IsCopyEnabled="False" makes the viewer leave the Copy command alone: Ctrl+C goes up to your command binding, and you decide what goes on the clipboard. Copy() and CopyMarkdown() still work when you call them.

MainWindow.xaml:

<Window.CommandBindings>
    <CommandBinding Command="Copy" CanExecute="OnCanCopy" Executed="OnCopy" />
</Window.CommandBindings>

<ScrollViewer>
    <md:MarkdownViewer x:Name="Viewer" Markdown="{Binding Text}" IsCopyEnabled="False" />
</ScrollViewer>

MainWindow.xaml.cs, in the window class:

private void OnCanCopy(object sender, CanExecuteRoutedEventArgs e)
    => e.CanExecute = Viewer.SelectionLength > 0;

private void OnCopy(object sender, ExecutedRoutedEventArgs e)
    => Clipboard.SetText(Viewer.SelectedMarkdown);

Context menu

By default the viewer has a menu with «Copy», «Copy as Markdown» and «Select All». Its captions are theme keys — translate them as described in Theming.

Your own menu is the ordinary ContextMenu property; its commands are pointed at the viewer with CommandTarget.

MainWindow.xaml:

<md:MarkdownViewer x:Name="Viewer" Markdown="{Binding Text}">
    <md:MarkdownViewer.ContextMenu>
        <ContextMenu>
            <MenuItem Command="Copy"
                      CommandTarget="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
            <MenuItem Header="Search the web" Click="OnSearchWeb" />
        </ContextMenu>
    </md:MarkdownViewer.ContextMenu>
</md:MarkdownViewer>

MainWindow.xaml.cs, in the window class (using System.Diagnostics;):

private void OnSearchWeb(object sender, RoutedEventArgs e)
{
    var query = Uri.EscapeDataString(Viewer.SelectedText);
    Process.Start(new ProcessStartInfo($"https://duckduckgo.com/?q={query}") { UseShellExecute = true });
}

To change the menu of every viewer, define your own resource with the key Md.ContextMenu and x:Shared="False" in the application resources. ContextMenu="{x:Null}" on a viewer removes the menu.

Code blocks

A code block has its own copy button that copies the whole code — see Code Blocks.

Beresta.Markdown.Wpf

Basics

Working with Text

Appearance

Integration

Editing

Your Own Syntax

Ready-made Extensions


По-русски

Основы

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

Оформление

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

Правка

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

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

Clone this wiki locally