【发布时间】:2020-04-19 13:57:13
【问题描述】:
我有一些硬编码的 html:
string myHtml = "<html>some html</html>"
如何将其设置为我的 WebView 源?像这样的:
webView.HtmlSource = myHtml;
【问题讨论】:
我有一些硬编码的 html:
string myHtml = "<html>some html</html>"
如何将其设置为我的 WebView 源?像这样的:
webView.HtmlSource = myHtml;
【问题讨论】:
一般来说,我们使用WebView.NavigateToString(htmlstring);来加载和显示html字符串。对于 WebView 的来源,仅适用于 Uri 参数。但是您可以为 WebView 创建一个附加属性,如 HtmlSource,并在它更改时调用 NavigateToString 进行加载。
public class MyWebViewExtention
{
public static readonly DependencyProperty HtmlSourceProperty =
DependencyProperty.RegisterAttached("HtmlSource", typeof(string), typeof(MyWebViewExtention), new PropertyMetadata("", OnHtmlSourceChanged));
public static string GetHtmlSource(DependencyObject obj) { return (string)obj.GetValue(HtmlSourceProperty); }
public static void SetHtmlSource(DependencyObject obj, string value) { obj.SetValue(HtmlSourceProperty, value); }
private static void OnHtmlSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
WebView webView = d as WebView;
if (webView != null)
{
webView.NavigateToString((string)e.NewValue);
}
}
}
.xaml:
<WebView x:Name="webView" local:MyWebViewExtention.HtmlSource="{x:Bind myHtml,Mode=OneWay}"></WebView>
【讨论】: