Skip to content

How to use

whistyun edited this page Jul 8, 2023 · 5 revisions

Markdown.Avalonia supports three methods to render markdown.

  1. Load .md from AvaloniaResource
  2. Write markdown in xaml
  3. With binding
  4. Setup AvaloniaEdit for syntax hightlighting

Load .md from AvaloniaResource

MarkdownScrollViewer.Source accept url. if you set avares, http or file to this property. MarkdownScrollViewer reference it and render it.

Sample

.csproj

...
<ItemGroup>
  <AvaloniaResource Include="MdTxt\Test.md" />
</ItemGroup>
...

.axaml

<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:md="https://github.com/whistyun/Markdown.Avalonia"
             x:Class="HowToUse.WriteMarkdownInXaml">

  <md:MarkdownScrollViewer
      Source="avares://YourAssemblyName/MdTxt/Test.md"/>

</UserControl>

Write markdown in xaml

MarkdownScrollViewer's Content accept indented markdown. indent-processing-rule is similar to flexible_heredoc_nowdoc_syntaxes in PHP7.3: the indentation of the closing tag dictates the amount of whitespace to strip from each line.

Sample

<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:md="https://github.com/whistyun/Markdown.Avalonia"
             x:Class="HowToUse.WriteMarkdownInXaml">

  <md:MarkdownScrollViewer xml:space="preserve">
    # Heading1

    Hello Markdown.Avalonia!

    * listitem1
    * listitem2

    | col1 | col2 | col3 |
    |------|------|------|
    | one  |------|------|
    | two  |------|------|

  </md:MarkdownScrollViewer>

</UserControl>

view

With binding

If you want to change the content dinamically ( for example view help text for user selected content), I suggest to use binding.

MarkdownScrollViewer has Markdown property to use binding.

Sample

xaml

<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:HowToUse;assembly=HowToUse"
             xmlns:md="https://github.com/whistyun/Markdown.Avalonia"
             x:Class="HowToUse.WriteMarkdownInXaml">

  <UserControl.DataContext>
    <local:UseBindingViewModel/>
  </UserControl.DataContext>

  <md:MarkdownScrollViewer
      Markdown="{Binding MdText}"/>

</UserControl>

viewmodel

using ReactiveUI;

namespace HowToUse
{
    public class UseBindingViewModel : ReactiveObject
    {
        private string _MdText;
        public string MdText
        {
            get => _MdText;
            set => this.RaiseAndSetIfChanged(ref _MdText, value);
        }
    }
}