Just a little post to point out a hidden gem if you are a .NET developer creating a Metro style app: you can bind to anonymous types. This came up in a discussion with a customer today that I was having and, frankly, I never tried it until then because my mind was back in Silverlight where this isn’t possible. There may not be a tone of cases where this is valuable for you, but knowing it is there may help.
Let’s assume I have a basic class Person:
And in my application I have a list of that Person type that I somehow received. In this example, I’m just hard-coding it right now.
I can then decide I want to bind to a ListView control which has a particular template:
Notice that I’m binding to properties (TheName and GuysAge) that don’t exist on my Person class? In my code, I can then create a LINQ query to filter out only the “dudes” from my list and bind that result:
The result is that my ListView now shows 2 people in the list. Nice.
Get in the real world
Now I would probably agree that since you already have a strongly-typed class this is probably not the use case here. It certainly might be helpful, but you already have a class (and in this example, one that you completely control so you could shape it to be what you really need). What about those times you don’t have a class or you don’t own the type coming back? JSON ring a bell? Using the sample JSON response (I’m not focusing on how to retrieve data here just how to bind to it) from Twitter APIs, we can demonstrate how this might be more helpful. Here’s the Twitter JSON data I’m referring to in this example: Twitter Mentions API.
My app wants to retrieve and bind to Twitter data but I don’t really want to have a “TwitterResponse” data type that I have to serialize in/out in my code. The mention data is an array of mentions. For the sake of simplicity I’ve basically put my JSON string in a file rather than confuse this sample in how to work with Twitter. My code looks like this (assume that ‘data’ is the resulting Twitter mentions JSON string:
Notice the LINQ query for creating a “new” type that I will bind to my ListView. In my XAML I have a simple DataTemplate to demonstrate:
The result is me being able to create a LINQ query and create a new anonymous type and directly bind to it.
Voila! Perhaps you already discovered this little gem and are using it. It is a welcome addition to the data binding story for Metro style app development with XAML and .NET! Of course the same benefit can be had for XML data using XLINQ queries, so while this example is for JSON data, really any source data applies…it is all about that new anonymous type you create!
Hope this helps!