using Microsoft.Phone.Controls;
using System;
using System.Windows;
namespace CommonUI.AttachedProperty
{
/// <summary>
/// Atttached property for WebBrowser control,bind a html string to display as web page in web browser
/// </summary>
public class WebBrowserContentBinding
{
/// <summary>
/// attached property Content
/// </summary>
public static readonly DependencyProperty ContentProperty = DependencyProperty.RegisterAttached("Content",typeof(string),typeof(WebBrowserContentBinding),new PropertyMetadata(OnContentChanged));
/// <summary>
/// Get value of attached property Content
/// </summary>
/// <param name="obj">WebBrowser object</param>
/// <returns>the value of Content property </returns>
public static string GetContent(WebBrowser obj)
{
return (string)obj.GetValue(ContentProperty);
}
/// <summary>
/// Set the value of attached property Content
/// </summary>
/// <param name="obj">WebBrowser object</param>
/// <param name="content">the value that set to property Content</param>
public static void SetContent(WebBrowser obj,string content)
{
obj.SetValue(ContentProperty,content);
}
private static void OnContentChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
var webBrowser = d as WebBrowser;
if (webBrowser == null)
{
throw new InvalidOperationException(string.Format("WebBrowserContentBinding attached property only can be used in WebBrowser,you are using in {0}",d.GetType().Name));
}
webBrowser.LoadCompleted += WebBrowser_LoadCompleted;
webBrowser.NavigateToString(e.NewValue.ToString());
}
private static void WebBrowser_LoadCompleted(object sender,System.Windows.Navigation.NavigationEventArgs e)
{
var wb = sender as WebBrowser;
wb.LoadCompleted -= WebBrowser_LoadCompleted;
wb.Visibility = Visibility.Visible;
}
}
}