Thursday, October 9, 2008

Silverlight 2.0 Interacting with html

With SilverLight 2.0 you can interact and handle events with the html elements on your page.  Here is a simple example that places a select (drop down control) on a web page which will change the color of a ellipse on a SilverLight app.  So lets start with the html

?
<body style="height: 100%; margin: 0;">
    <form id="form1" runat="server" style="height: 100%;">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <br />
    <span>Select a Color </span>
    <select id="ddColor">
        <option>Red</option>
        <option>Blue</option>
        <option>Green</option>
    </select>
    <br />
    <br />
    <div style="height: 100%;">
        <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/HtmlAndSilverlight.xap"
            MinimumVersion="2.0.30923.0" Width="100%" Height="100%" />
    </div>
    </form>
</body>


Now the XAML

?
<UserControl x:Class="HtmlAndSilverlight.Page"
    Width="400" Height="300">
    <Canvas x:Name="LayoutRoot" Background="Tan" >
        <Ellipse x:Name="el" Width="400" Height="300" Fill="Red"></Ellipse>
    </Canvas>
</UserControl>

Now build the app so we have intellisense for the controls.  Ok first off lets get access to the drop down (select) on the web page. Then we can use AttachEvent to handle the onchange event.   

?
Dim cbo As HtmlElement
Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
    cbo = HtmlPage.Document.GetElementById("ddColor")
    cbo.AttachEvent("onchange", AddressOf ColorChanged)
End Sub

Once the user selects a color we will change the color of the ellipse.  Here is the complete code listing

?
Imports System.Windows.Browser
 
Partial Public Class Page
    Inherits UserControl
 
    Public Sub New()
        InitializeComponent()
    End Sub
    Dim cbo As HtmlElement
    Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        cbo = HtmlPage.Document.GetElementById("ddColor")
        cbo.AttachEvent("onchange", AddressOf ColorChanged)
    End Sub
 
    Private Sub ColorChanged(ByVal sender As Object, ByVal e As HtmlEventArgs)
        Dim x = CInt(cbo.GetAttribute("selectedIndex").ToString)
        Select Case x
            Case 0
                el.Fill = New SolidColorBrush(Colors.Red)
            Case 1
                el.Fill = New SolidColorBrush(Colors.Blue)
            Case 2
                el.Fill = New SolidColorBrush(Colors.Green)
        End Select
    End Sub
End Class


Hope this helps