Skip to content

Instantly share code, notes, and snippets.

@ThomasPe
Last active November 11, 2017 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasPe/7c179c2732b419ef359219b83692a1b0 to your computer and use it in GitHub Desktop.
Save ThomasPe/7c179c2732b419ef359219b83692a1b0 to your computer and use it in GitHub Desktop.
This is an extension to the XAML WebView for invoking scripts from a ViewModel
public static class WebViewExtensions
{
/// <summary>
/// Using a DependencyProperty as the backing store for Content Uri.  This binding Content Uri.
/// </summary>
public static readonly DependencyProperty InvokeScriptProperty = DependencyProperty.RegisterAttached(
"InvokeScript",
typeof(string),
typeof(WebViewExtensions),
new PropertyMetadata(String.Empty, OnInvokeScriptChanged));
/// <summary>
/// Gets Uri source associated with the <see cref="WebView"/>
/// </summary>
/// <param name="obj">The <see cref="DependencyObject"/> that has the content uri.</param>
/// <returns>HTML content</returns>
public static string GetInvokeScript(DependencyObject obj)
{
return (string)obj.GetValue(InvokeScriptProperty);
}
/// <summary>
/// Sets HTML from the <see cref="WebView"/>
/// </summary>
/// <param name="obj">The <see cref="DependencyObject"/> that content uri is being set to.</param>
/// <param name="value">HTML content</param>
public static void SetInvokeScript(DependencyObject obj, string value)
{
obj.SetValue(InvokeScriptProperty, value);
}
private static void OnInvokeScriptChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
WebView wv = d as WebView;
var script = e.NewValue as string;
if (script == null)
{
return;
}
wv?.InvokeScriptAsync("eval", new string[] { script });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment