Thursday, May 27, 2010

Dynamically Load xaml in Silverlight

Introduction:

Let's have a scenario. Suppose you have a login page and a registration page or typically two separate xamls. Now you have only one user control and inside its layout root you have a grid. When the page loads first time you need to show the login window. But when user clicks something say one button named "Register yourself" you want to load your customized registration xamls inside the same grid. So the scenario is you have two xamls and you need to load it dynamically. This is known as dynamically loading of xamls.

Approach:

For this, I would like to store the xaml on the web. You can have it in your local drives also but putting it on the web (typically in SharePoint list) will serve the purpose. We will try to make a Synchronous call like this :

public class SyncJSWS
   {
       private static void createDiv()
       {
       }
       public static string LoadStringFromUrl(string url)
       {
           return callService(url);
       }
}
public static string callService(string url)
{
 HtmlPage.Window.Eval("if(typeof XMLHttpRequest==\"undefined\"){XMLHttpRequest=function(){var a=[\"Microsoft.XMLHTTP\",\"MSXML2.XMLHTTP\",\"MSXML2.XMLHTTP.3.0\",\"Msxml3.XMLHTTP\"];for(var b=0;b<a.length;b++){try{return new ActiveXObject(a[ b ]);}catch(ex){}}};}");

 ScriptObject xhr = HtmlPage.Window.CreateInstance("XMLHttpRequest");
           xhr.Invoke("open", "GET", url, false);
           xhr.Invoke("setRequestHeader", "Content-Type", "text/xml; charset='utf-8'");
           createDiv();
           xhr.Invoke("send", "");
           Double status = (Double)xhr.GetProperty("status");
           string statusText = (string)xhr.GetProperty("statusText");
           if (status != 200)
           {
               string responseText = (string)xhr.GetProperty("responseText");
               if (!string.IsNullOrEmpty(responseText))
               {
                   throw new Exception(responseText);
               }
               else
               {
                   throw new Exception(statusText);
               }
           }
           else
           {
               string responseText = (string)xhr.GetProperty("responseText");
               return responseText;
           }
       }

The XamlReader class will serve the purpose of loading the xaml automatically.

Read more: C# Corner

Posted via email from jasper22's posterous