Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

WPF: Binding to Anonymous Types from LINQ

DZone's Guide to

WPF: Binding to Anonymous Types from LINQ

·
Free Resource

When 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

 

Topics:

Published at DZone with permission of Pete Brown. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}