My data context object contains a string property that returns html that I need to display in WebBrowser control; I can't find any properties of WebBrowser to bind it to. Any ideas?
1 Answer
The WebBrowser has a NavigateToString method that you can use to navigate to HTML content. If you want to be able to bind to it, you can create an attached property that can just call the method when the value changes:
public static 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 d, DependencyPropertyChangedEventArgs e)
{
WebBrowser wb = d as WebBrowser;
if (wb != null)
wb.NavigateToString(e.NewValue as string);
}
}
And you would use it like so (where lcl is the xmlns-namespace-alias):
<WebBrowser lcl:BrowserBehavior.Html="{Binding HtmlToDisplay}" />
6 Comments
Adam Larsen
Second argument for OnHtmlChanged should be of type DependencyPropertyChangedEventArgs.
scott.smart
I added this to my code but it does not allow me to edit (a required feature). I am fairly new to wpf so I am unsure of what to change to allow me to edit the html.
Abe Heidebrecht
The WebBrowser control displays HTML. If you want to be able to edit the HTML, you will have to use another control, like TextBox or RichTextBox.
Simon_Weaver
this answer is incomplete - what's PinnedInstrumentsViewModel, in which class do I even put this? this is basically the same answer but ready to go : stackoverflow.com/a/4204350/16940
Abe Heidebrecht
@Simon_Weaver, you're correct, and that was a dumb type. I've updated it so it makes more sense.
|