WPF: Binding to Anonymous Types from LINQ
Join the DZone community and get the full member experience.
Join For FreeWhen doing some writing on Binding for WPF 4, it occurred to me that many folks don't realize that in WPF, we've long been able to bind to anonymous types returned from LINQ statements, as long as we have property names. Here's a quick example that does a product of two lists to generate some test data:
XAML
<ListBox x:Name="MyListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10">
<TextBlock Text="{Binding Name}" FontSize="18" />
<TextBlock Text="{Binding Role}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
string[] names = new string[]
{
"Captain Avatar", "Derek Wildstar", "Queen Starsha"
};
string[] roles = new string[]
{
"Hero", "Captain", "Queen of Iscandar"
};
MyListBox.ItemsSource = from n in names
from r in roles
select new { Name = n, Role = r };
}
Result
Published at DZone with permission of Pete Brown. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments