Over a million developers have joined DZone.

WPF: Binding to Anonymous Types from LINQ

·

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.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}