在WP开发中,有时候会用到WebBrowser控件来展示一些html内容,这个控件有很多局限性,比如不支持绑定内容,这样的MVVM模式中就无法进行内容的绑定。为了实现这个目的,需要扩展一下,具体代码如下:

/// <summary>
    /// 用于绑定WebBrowser控件的html内容 用法:ext:WebBrowserProperties.Body="{Binding CurrentArticleItem.Html}"
    /// </summary>
    public class WebBrowserProperties
    {
        public static readonly DependencyProperty BodyProperty =
            DependencyProperty.RegisterAttached("Body", typeof(string), typeof(WebBrowserProperties), new PropertyMetadata(OnBodyChanged));

        public static string GetBody(DependencyObject dependencyObject)
        {
            return (string)dependencyObject.GetValue(BodyProperty);
        }

        public static void SetBody(DependencyObject dependencyObject, string body)
        {
            dependencyObject.SetValue(BodyProperty, body);
        }

        private static void OnBodyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var webBrowser = (WebBrowser)d;
            webBrowser.NavigateToString((string)e.NewValue);
        }
    }

使用时,在XAML代码中加上如下的部分

ext:WebBrowserProperties.Body="{Binding CurrentArticleItem.Html}"

就可以支持绑定了。

相关文章:

  • 2021-11-06
  • 2021-12-26
  • 2022-01-01
  • 2021-06-10
  • 2022-12-23
  • 2022-01-31
  • 2021-06-30
猜你喜欢
  • 2022-12-23
  • 2021-12-08
  • 2022-12-23
  • 2022-02-09
  • 2021-06-25
  • 2021-08-29
  • 2021-06-04
相关资源
相似解决方案