I found an example online that explains how to perform databinding to a ListBox control using LINQ in WPF. The example works fine but when I replicate the same code in Silverlight it doesn’t work. Is there a fundamental difference between Silverlight and WPF that I’m not aware of?
Here is an Example of the XAML:
<ListBox x:Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" FontSize="18"/>
<TextBlock Text="{Binding Role}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is an example of my code behind:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
string[] names = new string[] { "Captain Avatar", "Derek Wildstar", "Queen Starsha" };
string[] roles = new string[] { "Hero", "Captain", "Queen of Iscandar" };
listBox1.ItemSource = from n in names from r in roles select new { Name = n, Role = r}
}
Silverlight does not support binding to anonymous types. (To be technically correct, Silverlight does not support reflecting against internal types, and since anonymous types are internal, this doesn’t work). See this article for a simple workaround- you will merely need to create a model class to hold the data.