我可以将 HTML 绑定到 WPF Web 浏览器控件吗? [英] Can I bind HTML to a WPF Web Browser Control?
问题描述
假设我有一个属性 HTML(字符串).我可以将它绑定到 WPF WebBrowser 控件吗?我需要一个 URI 的 Source 属性,但是如果我想在内存中呈现一个 HTML 字符串,我可以这样做吗?我正在使用 MVVM,所以我认为使用 webBrowser1.NavigateToString()
等方法更难?因为我不知道控件名称?
Suppose I have a property HTML (string). Can I bind that to a WPF WebBrowser control? There is the Source property where I need a URI, but if I have a HTML string in memory I want to render, can I do that? I am using MVVM, so I think its harder to use methods like webBrowser1.NavigateToString()
etc? cos I won't know the control name?
推荐答案
参见 这个 问题.
总而言之,首先为 WebBrowser 创建一个附加属性
To summarize, first you create an Attached Property for 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
And then you can Bind to your html string and NavigateToString will be called everytime your html string changes
<WebBrowser local:BrowserBehavior.Html="{Binding MyHtmlString}" />
这篇关于我可以将 HTML 绑定到 WPF Web 浏览器控件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!