Welcome to Pete Brown's 10rem.net

First time here? If you are a developer or are interested in Microsoft tools and technology, please consider subscribing to the latest posts.

You may also be interested in my blog archives, the articles section, or some of my lab projects such as the C64 emulator written in Silverlight.

(hide this)

WPF: Binding to Anonymous Types from LINQ

Pete Brown - 12 April 2010

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

image

     
posted by Pete Brown on Monday, April 12, 2010
filed under:      

6 comments for “WPF: Binding to Anonymous Types from LINQ”

  1. David Dermansays:
    Does anyone know if we will ever have the ability to do this in Silverlight. The last time I checked binding to an anoymouse type returned from linq queries throws an exception in Silverlight.
  2. Marc Zisssays:
    What about:

    string[] names = new string[]

    {

    "Deslock", "Deslock", "Deslock", "Deslock"

    };


    MyListBox.ItemsSource = from n in names
    select new { Name = n };


    ps thanks for coming up and presenting for Philly.Net code camp on Saturday we're getting great feedback
  3. Nirsays:
    The code missed one small piece: "{Binding Role, Mode=OneTime}", with default mode the code breaks as anonymous types have readonly properties, which does not work with OneWay or OneWayToSource binding which is default.

    <ListBox x:Name="MyListBox" >
    <ListBox.ItemTemplate>
    <DataTemplate>
    <StackPanel Margin="10">
    <TextBox Text="{Binding Name, Mode=OneTime}" FontSize="18"/>
    <TextBox Text="{Binding Role, Mode=OneTime}" />
    </StackPanel>
    </DataTemplate>
    </ListBox.ItemTemplate>
    </ListBox>

Comment on this Post

Remember me