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:
1: public class Person
2: {
3: public int Age { get; set; }
4: public string FirstName { get; set; }
5: public string Gender { get; set; }
6: }
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.
1: List<Person> people = new List<Person>();
2: people.Add(new Person() { Age = 38, FirstName = "Tim", Gender = "Male" });
3: people.Add(new Person() { Age = 9, FirstName = "Zoe", Gender = "Female" });
4: people.Add(new Person() { Age = 5, FirstName = "Zane", Gender = "Male" });
I can then decide I want to bind to a ListView control which has a particular template:
1: <ListView x:Name="PeopleList" Width="500" Height="300">
2: <ListView.ItemTemplate>
3: <DataTemplate>
4: <StackPanel Orientation="Horizontal">
5: <TextBlock Text="{Binding TheName}" Margin="0,0,10,0" />
6: <TextBlock Text="{Binding GuysAge}" />
7: </StackPanel>
8: </DataTemplate>
9: </ListView.ItemTemplate>
10: </ListView>
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:
Read more: Tim
QR: