In this article I will show you calling of JavaScript function from Silverlight. It is very simple and straight forward. Assume you have a JavaScript function on an aspx page as below:SilverlightTestPage.aspx <script type="text/javascript" language="javascript" > function callmeonPageLoad() { alert("Hello Javascript from Silvertlight"); } </script>If you want to call this JavaScript function on a page load of the Silverlight page then you will have to add the namespace: And in the constructor of the page call it as below:MainPage.xaml.csusing System.Windows.Controls;using System.Windows.Browser; namespace SilverlightApplication7{ [ScriptableType] public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); HtmlPage.RegisterScriptableObject("MainPage", this); HtmlPage.Window.Invoke("callmeonPageLoad"); } }}If you notice in above code you will find that MainPage is attributed with a ScriptableType. On running Silverlight application you will be getting output as below:On your XAML, if you have a textbox like below:If you want to access and change the value of the textbox txtName in JavaScript then it too is very simple. Create a JavaScript function as below:SilverlightTestPage.aspx
<script type="text/javascript"> function UpdatingTextBoxValue(sender) { var txtBlockFromSL = sender.FindName("txtName"); alert(txtBlockFromSL.text); txtBlockFromSL.Text = "Salsa "; alert(txtBlockFromSL.Text); } </script>txtName is name of the Silverlight text box.And on the page load on aspx page add a param:If you have a function in managed code and you want to access that from JavaScript. Assume you have a function as below:MainPage.xaml.cs [ScriptableMember] public void SilverLightFunction(string txtToUPdate) { txtName.Text = txtToUPdate; }You can call this function from JavaScript as below, <script type="text/javascript"> function UpdatingTextBoxValue(sender) { var host = sender.GetHost(); host.content.MainPage.SilverLightFunction("Dhananjay"); } </script>This was all about various ways to work with Silverlight and JavaScript. I hope this article was useful. Thanks for reading.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: