Mega Code Archive
Calling a JavaScript Method from Managed Code
//File: Page.xaml.cs
using System;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Media;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Page_Loaded);
SizeChanged += new SizeChangedEventHandler(Page_SizeChanged);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
HtmlPage.RegisterScriptableObject("Page", this);
HtmlDocument doc = HtmlPage.Document;
doc.GetElementById("Button1").AttachEvent("click",new EventHandler(this.InvokedFromHtmlButtonClick));
}
void Page_SizeChanged(object sender, SizeChangedEventArgs e)
{
HtmlDocument doc = HtmlPage.Document;
doc.GetElementById("silverlightControlHost").SetStyleAttribute("width",this.Width.ToString());
}
[ScriptableMember]
public string GetMyBackgroundColor()
{
Brush b = LayoutRoot.Background;
if (b is SolidColorBrush)
{
SolidColorBrush scb = b as SolidColorBrush;
return scb.Color.R.ToString("X2") + scb.Color.G.ToString("X2") +
scb.Color.B.ToString("X2");
}
else if (b is GradientBrush)
{
GradientBrush gb = b as GradientBrush;
GradientStop gs = gb.GradientStops[0];
return gs.Color.R.ToString("X2") + gs.Color.G.ToString("X2") +gs.Color.B.ToString("X2");
}
else
return "#FFFFFF";
}
private void InvokedFromHtmlButtonClick(object o, EventArgs e)
{
MessageTextBlock.Text = "HTML button clicked at " + DateTime.Now.ToString();
}
}
}