Binding html string content to Webview in xaml

后端 未结 1 903
忘了有多久
忘了有多久 2021-01-02 08:26

I have a webview in my xaml which looks as follows :


And, in my codebehind I have a variable called \

1条回答
  •  执笔经年
    2021-01-02 08:57

    The HtmlString property does not exist on WebView (only the Source property which is an Uri). But what you can do is to define yourself a new HtmlString attached property for WebView. Just create the following class :

    namespace YOURNAMESPACE
    {
        class MyProperties
        {
         // "HtmlString" attached property for a WebView
         public static readonly DependencyProperty HtmlStringProperty =
            DependencyProperty.RegisterAttached("HtmlString", typeof(string), typeof(MyProperties), new PropertyMetadata("", OnHtmlStringChanged));
    
         // Getter and Setter
         public static string GetHtmlString(DependencyObject obj) { return (string)obj.GetValue(HtmlStringProperty); }
         public static void SetHtmlString(DependencyObject obj, string value) { obj.SetValue(HtmlStringProperty, value); }
    
         // Handler for property changes in the DataContext : set the WebView
         private static void OnHtmlStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
         {
            WebView wv = d as WebView; 
            if (wv != null) 
            { 
                wv.NavigateToString((string)e.NewValue); 
            } 
         }
        }
    }
    

    Supposing that your DataContext field is called CurrentHtmlString, then you can use this new WebView's HtmlString property in your XAML file to bind it, with a syntax like :

     
    

    Normally you already have the following line at the top of your XAML file :

    xmlns:local="using:MYNAMESPACE"
    

    You can find more explanation here from Rob Caplan : http://blogs.msdn.com/b/wsdevsol/archive/2013/09/26/binding-html-to-a-webview-with-attached-properties.aspx

    0 讨论(0)
提交回复
热议问题