Dealing with Silverlight InitParms
I’ve found the best way access initParams throughout your Silverlight Application is to put them in a global static dictionary. This is how I setup my initParms dictionary.
First we need to set an initParams in our ASPX Page:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <div id="silverlightControlHost"> <object width="100%" height="100%" type="application/x-silverlight-2" data="data:application/x-silverlight-2,"> <param name="source" value="ClientBin/initParamsDemo.xap" /> <param name="onError" value="onSilverlightError" /> <param name="background" value="white" /> <param name="minRuntimeVersion" value="3.0.40818.0" /> <param name="autoUpgrade" value="true" /> <param name="initParams" value="ServiceURL=http://localhost:8000/service1.svc" /> < a style="text-decoration: none;" href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0"> <img style="border-style: none;" src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" /> </a> </object> </div> |
Next we need to create our static dictionary in App.xaml.cs and assign the dictionary in the startup event.
1 2 3 4 5 6 7 | public static IDictionary<string, string> AppParams; private void Application_Startup(object sender, StartupEventArgs e) { this.RootVisual = new MainPage(); AppParams = e.InitParams; } |
When you want to access your param you simply use grab if from the dictionary using the key.
1 | App.AppParams["ServiceURL"] |
We can’t always trust that the initParam is set you should check to make sure it’s in the dictionary before using it.
1 2 3 4 5 6 7 8 | if (App.AppParams.ContainsKey("ServiceURL")) { // Do Something with: App.AppParams["ServiceURL"] } else { // Handle error</code></em></span> } |
Leave a Reply