我有一些硬编码的html:
string myHtml = "<html>some html</html>"
如何将其设置为WebView源?像这样:
webView.HtmlSource = myHtml;
答案 0 :(得分:0)
通常,我们使用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>
有关更多详细信息,请参阅Binding HTML to a WebView with Attached Properties。