见
this
问题。
总而言之,首先要为WebBrowser创建一个附加属性
public class BrowserBehavior
{
public static readonly DependencyProperty HtmlProperty = DependencyProperty.RegisterAttached(
"Html",
typeof(string),
typeof(BrowserBehavior),
new FrameworkPropertyMetadata(OnHtmlChanged));
[AttachedPropertyBrowsableForType(typeof(WebBrowser))]
public static string GetHtml(WebBrowser d)
{
return (string)d.GetValue(HtmlProperty);
}
public static void SetHtml(WebBrowser d, string value)
{
d.SetValue(HtmlProperty, value);
}
static void OnHtmlChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
WebBrowser webBrowser = dependencyObject as WebBrowser;
if (webBrowser != null)
webBrowser.NavigateToString(e.NewValue as string ?? " ");
}
}
然后可以绑定到HTML字符串,每次更改HTML字符串时都会调用NavigateToString。
<WebBrowser local:BrowserBehavior.Html="{Binding MyHtmlString}" />