Friday, October 2, 2009

CallingSilverlightFromASPXPage

While the page load and to populate silverlight control, in Page_Load() of .aspx following has to be done.
multiFileUploaderSilverlightControl.InitParameters = string.Format( "FileName={0},SnapshotImage1={1}", "MultiFileUploader", snapshotImage);

 

To access the values from the above passed method, in the .xaml page’s constructor,


public MultiFileUploader(IDictionary<string, string> param)
{
   InitializeComponent();
   HtmlPage.RegisterScriptableObject(param["FileName"], this);
   if (param.Count > 0)
   {
      _snapShotImage1 = param["SnapshotImage1"];
   }
}
To call a specific usercontrol from the silverlight application, the name has to set in the InitParameters, in this case “MultiFileUploader” and this will be checked in the App.xaml.cs as shown below,
private void Application_Startup(object sender, StartupEventArgs e)
{
  if (e.InitParams != null)
  {
     foreach(var item in e.InitParams)
     {
         Resources.Add(item.Key, item.Value);
     }
  }
   if (Current.Resources.Contains("FileName"))
   {
      fileName = Convert.ToString(Current.Resources["FileName"]);
   }
   if (!string.IsNullOrEmpty(fileName))
   {
      switch (fileName)
      {
         case "MultiFileUploader":
            this.RootVisual = new MultiFileUploader(e.InitParams);
            break;
      }
   }
}

 
To call a method from .aspx page to .xaml(silverlight) page, the following has to be done.
First decorate the class in the xaml page with the attribute [ScriptableType] as
[ScriptableType]
public partial class MultiFileUploader : UserControl
{   }
and decorate the method with the attribute [ScriptableMember]

[ScriptableMember]
public void UploadFiles(string param)
{   }

so that this method can be called from .aspx’s javascript method as shown below
var silverligthControl = document.getElementById('multiFileUploaderSilverlightControl'); silverligthControl.Content.MultiFileUploader.UploadFiles(param);
where, multiFileUploaderSilverlightControl is silverlight control added in .aspx page and in the next line we have called
SilverlightControlName.Content.ClassName.MethodName(parameter)

To call a method from .xaml page to .aspx page, the following has to be done.
HtmlPage.Window.Invoke("ValueFromMultiFileUploaderXaml", param);
In the above line we invoke ValueFromMultiFileUploaderXaml Javascript method which is in .aspx page

To access the values passed from the above javascript method call,

function ValueFromMultiFileUploaderXaml(fileDetails)
{
   if (fileDetails.length > 0)
   {
      var param = fileDetails[0];
   }
}