Naftis
Naftis

Reputation: 4559

WP7 WebBrowser in MVVM

I am using a WebBrowser control in a MVVM WP7 application. I used an attached property to allow binding the control to a generated HTML string, as explained in http://compiledexperience.com/blog/posts/binding-html-to-the-web-browser-control . The attached property is bound to my VM which generates HTML code. Problem is that the code is generated before the control has fully loaded, so that I get an exception when the VM property changes:

You cannot call WebBrowser methods until it is in the visual tree.

I could use some "hack" like avoiding the binding at all, and rather firing an event from my VM and letting the view handle it and pospone the call to WebBrowser.NavigateToString until it's loaded, but I was wondering if anyone could suggest a better, more elegant way...

Upvotes: 2

Views: 1030

Answers (1)

ColinE
ColinE

Reputation: 70122

I think the best thing to do is fix the attached property so that it works properly. Here's a suggestion:

private static void OnHtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var browser = d as WebBrowser;

    if(browser == null)
        return;

    var html = e.NewValue.ToString(); 

    try
    {
        browser.NavigateToString(html);
    }
    catch (Exception ex)
    {
        browser.Loaded += (s,e3) =>
           {
               browser.NavigateToString(html);
           }
    }

}

The code above tries to display the HTML, if an exception is thrown, the Loaded event is handled (which occurs when a control has been rendered within the visual tree), then the HTML is supplied.

There might be a better methods than try / catch, it is worth checking the API for the WebControl. However, the above should work.

Upvotes: 6

Related Questions