I do not think, this is a recurring Silverlight pattern. Once in a while, we run into a situation where we need to work with dynamic classes. One best example is creating pivot using Silverlight. Well, by default when I say pivot, it is supposed to be read only control. Component One has a very powerful pivot control for Silverlight called OLAP for Silverlight. Lets say, you need work on the pivot data but you need to edit it, even then, you do not need to create a run time class to solve the problem. You can get away without using run time classes. But for the fun of it, I thought I will see if we can solve the problem by creating the dynamic class.
As always I develop Silverlight MVVM application using Jounce. So is the case here as well. So what are we trying to do? Before we go into creating pivot class lets first look at a simple solution using dynamic. We are going to display a grid of text block to show first name, last name, age and salary like the following
Lets start with our simple XAML
In the XAML we are doing direct binding to the view model properties. Lets look at the View Model code for these properties
This code basically returns each property of person instance of a class. One would think it is a our favorite ‘Person’ class but that is the not the case. person is defined as
look at that we did not define the Person class rather we declared as a dynamic of type ExpandoObject. The beauty of this type is that, during run time you can add and remove members. Now the person is defined, how do we add properties to the class. Here is how, you can make members on the fly.
Please make sure you add Microsoft.CSharp.dll otherwise you will get a compile time error.
That is it, compile and run it, you will the result as shown in the beginning of the blog.
Hopefully you read through the MSDN reference on ExpandoObject. If you read all the way towards end, there is one section that is of very much interest to us. ‘Receiving Notifications of Property Changes’. As per MSDN, “ExpandObject class implements the INotifyPropertyChanged interface and can raise a PropertyChanged event when a member is added, deleted, or modified.” That is a very good news for us. But please don’t get carried away, there is a catch, it direct dynamic binding only works in WPF not in Silverlight. We will look at the issue in the next blog and see how we can solve it.