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>
<T开发者_高级运维extBlock 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.
public class MyItem
{
public string Name { get; set; }
public string Role { get; set; }
}
listBox1.ItemSource = from n in names from r in roles select new MyItem() { Name = n, Role = r}
In Silverlight you can not bind to anonymous types. Silverlight requires the type of the item being bound to be public
but anonymous types are by internal
.
You will need to to create a public type to carry your results:-
public class MyItem
{
public string Name {get; set; }
public string Role {get; set; }
}
now in your code:-
listBox1.ItemSource = from n in names from r in roles select new MyItem() { Name = n, Role = r}
精彩评论