How to set the HTML string in the webbrowser control in Windows Phone in MVVM context

The webbrowser control in Windows Phone can display HTML contained in a string. Unfortunately, this can't be done directly via binding, you have to use the NavigateToString(string) method and this can't be used in a full MVVM context !!

To be full MVVM compliant, you can create a new DependencyObject with a DependencyProperty.

  • Create a new class called BindingWebBrowser which inherit from DependencyObject, and create a new DependencyProperty for the HTMLString.
    public class HtmlStringBinding : DependencyObject
    {
        public static readonly DependencyProperty HtmlStringProperty =
            DependencyProperty.RegisterAttached(
            "HtmlString",
            typeof(string),
            typeof(HtmlStringBinding),
            new PropertyMetadata(OnHtmlStringPropertyChanged));
    
        private static void OnHtmlStringPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != e.OldValue)
            {
                WebBrowser wb = (WebBrowser)d;
                wb.NavigateToString((string)e.NewValue);
            }
        }
    
        public static void SetHtmlString(DependencyObject obj, string html)
        {
            obj.SetValue(HtmlStringProperty, html);
        }
    
        public static string GetHtmlString(DependencyObject obj)
        {
            return (string)obj.GetValue(HtmlStringProperty);
        }
    }
  • And that's it, you can now put the WebBrowser control in the page and add the binding to the DependencyProperty !
<phone:WebBrowser Ctrls:HtmlStringBinding.HtmlString="{Binding HtmlVale}" />



Enjoy !

Comments are closed

Hi there !

 

Specialized in .net technologies for many years, I am a technology fan in both asp.net and wpf/silverlight, using c# and .net 4.

Taking advantages of new opportunities offered by the Windows Azure platform and WP7, I develop applications for Windows 7 Phone, 2 of them are already available on the market place.


 

 

Month List