Sunday, February 24, 2013

Using reflection in Silverlight


Reflection is a technique, which provides objects that encapsulate assemblies, modules, and types. Using this technique, you can call a method or set/get values of properties of a class object during runtime.

Here is a sample code snippet.

private void HidePhotoControl()
{
if (_MainPage == null) return;
System.Type _MainPageClassType = _MainPage.GetType();
_ MainPageClassType.InvokeMember("DisablePhotoControl", BindingFlags.InvokeMethod, null, _MainPage, null);
}

 As you can see here, the _MainPage contains a “PhotoControl” and the aim is to disable it. There is a method on the _MainPage called ‘DisablePhotoControl();’. If this function is called then it will simply disable the photo control by turning off the visibility property of it.

 But how to call this function from a different class, assuming that this other class does not have access to the Mainpage class? This is where the reflection technique helps.

 As seen in the code snippet, first make sure the main page pointer is not null. Then get the class type of the main page pointer. Finally using the main page class type to invoke the method call.

 It works like a charm!

 Happy coding!

No comments:

Post a Comment

All Blogs so far ...