Last active
November 11, 2017 13:12
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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