Windows Phone中扩展WebBrowser使其支持绑定html内容

时间:2023-03-09 03:15:49
Windows Phone中扩展WebBrowser使其支持绑定html内容

在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}"

就可以支持绑定了。