Calling a JavaScript Method from Managed Code
<UserControl x:Class='SilverlightApplication3.MainPage'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
d:DesignWidth='640'
d:DesignHeight='480'>
<StackPanel x:Name="LayoutRoot">
<TextBlock x:Name="MessageTextBlock" Text="Your text goes here..." TextWrapping="Wrap"/>
<StackPanel Margin="4" Grid.Row="2" Grid.Column="1" >
<TextBox Background="{x:Null}" Height="Auto" x:Name="TextFirstName"
Width="Auto" Foreground="#FF0000FF" Text="Enter First Name"
TextWrapping="Wrap" TabIndex="0" BorderBrush="{x:Null}" Margin="2"/>
<TextBox Background="{x:Null}" Height="Auto" x:Name="TextLastName"
Width="Auto" Foreground="#FF0000FF" Text="Enter Last Name"
TextWrapping="Wrap" TabIndex="1" BorderBrush="{x:Null}" Margin="2"/>
<TextBox Background="{x:Null}" x:Name="TextFavoriteColor"
Width="Auto" Foreground="#FF0000FF" Text="Enter Favorite Color"
TextWrapping="Wrap" TabIndex="2" BorderBrush="{x:Null}" Margin="2"/>
</StackPanel>
</StackPanel>
</UserControl>
//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();
}
}
}
Related examples in the same category