Skip to content

Instantly share code, notes, and snippets.

@dansiegel
Created January 17, 2020 15:56
Show Gist options
  • Save dansiegel/2ee0d2e58ea4365dbe8a2ad0104e03a7 to your computer and use it in GitHub Desktop.
Save dansiegel/2ee0d2e58ea4365dbe8a2ad0104e03a7 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
using HeyRed.MarkdownSharp;
using System.Runtime.CompilerServices;
// https://www.nuget.org/packages/Markdown/
namespace AwesomeApp.Controls
{
public class MarkdownView : WebView
{
public static readonly BindableProperty MarkdownProperty =
BindableProperty.Create(nameof(Markdown), typeof(string), typeof(MarkdownView), null, propertyChanged: OnMarkdownPropertyChanged);
public static readonly BindableProperty OptionsProperty =
BindableProperty.Create(nameof(Options), typeof(MarkdownOptions), typeof(MarkdownView), null, propertyChanged: OnMarkdownPropertyChanged);
private static void OnMarkdownPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if(bindable is MarkdownView mdv)
{
mdv.GenerateMarkdownSource();
}
}
public string Markdown
{
get => (string)GetValue(MarkdownProperty);
set => SetValue(MarkdownProperty, value);
}
public MarkdownOptions Options
{
get => (MarkdownOptions)GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
protected override void OnPropertyChanging([CallerMemberName] string propertyName = null)
{
if (propertyName == nameof(Source))
{
if (Source != null)
{
Navigating -= MarkdownView_Navigating;
}
else
{
Navigating += MarkdownView_Navigating;
}
}
}
private void GenerateMarkdownSource()
{
if(string.IsNullOrEmpty(Markdown))
{
Source = null;
}
var options = Options;
if(options == null)
{
options = new MarkdownOptions
{
AutoHyperlink = true,
AutoNewLines = true,
LinkEmails = true,
QuoteSingleLine = true,
StrictBoldItalic = true
};
}
Markdown mark = new Markdown(options);
var html = $@"<!DOCTYPE html>
<html>
<body>
{mark.Transform(Markdown)}
</body>
</html>";
Source = new HtmlWebViewSource
{
Html = html
};
}
private void MarkdownView_Navigating(object sender, WebNavigatingEventArgs e)
{
if (Uri.TryCreate(e.Url, UriKind.Absolute, out var uri) && uri.Scheme == "https" || uri.Scheme == "http")
{
e.Cancel = true;
Xamarin.Essentials.Browser.OpenAsync(uri);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment