简体   繁体   English

MVVM中的WP7 WebBrowser

[英]WP7 WebBrowser in MVVM

I am using a WebBrowser control in a MVVM WP7 application. 我在MVVM WP7应用程序中使用WebBrowser控件。 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 . 我使用了一个附加属性,以允许将控件绑定到生成的HTML字符串,如http://compiledexperience.com/blog/posts/binding-html-to-the-web-browser-control中所述 The attached property is bound to my VM which generates HTML code. 附加属性绑定到生成HTML代码的VM。 Problem is that the code is generated before the control has fully loaded, so that I get an exception when the VM property changes: 问题是代码是在控件完全加载之前生成的,因此当VM属性更改时,我得到一个异常:

You cannot call WebBrowser methods until it is in the visual tree. 您不能调用WebBrowser方法,直到它出现在可视树中。

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... 我可以使用一些“ hack”之类的方法,例如完全避免绑定,而是从我的VM触发一个事件并让视图处理它,并在调用被加载之前对WebBrowser.NavigateToString进行调用,但是我想知道是否有人可以建议一个更好的方法,更优雅的方式...

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. 上面的代码尝试显示HTML,如果引发异常,则处理Loaded事件(在可视树中呈现控件时发生),然后提供HTML。

There might be a better methods than try / catch, it is worth checking the API for the WebControl . 可能有比try / catch更好的方法,值得检查WebControl的API。 However, the above should work. 但是,以上应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM