Dynamically Load xaml in Silverlight


HTML clipboard

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. We can have a method something like this:

public static object GetScreenFromWeb(string url)
 {
            string xaml = SyncJSWS.LoadStringFromUrl(url);
            return XamlReader.Load(xaml);
 }

Now we can call this method like this:

UIElement uie = UIHelper.GetScreenFromWeb("your web address") as UIElement;

Now you can place it inside one grid.

Up Next
    Ebook Download
    View all
    Learn
    View all