tags:

views:

27

answers:

1

I have just started using WPF and am having trouble data binding from the result of a Linq query to a ListView.

I have tried a number of combinations including setting the DataContext and ItemsSource to the query. As in:

listView.DataContext = (from person in People select person).ToList();

Then in the xaml setting the DisplayMemberBinding to {Binding Name} or {Binding /Name} etc.

I'm not worried about any updating either way other than just showing a list of items from the query at this stage.

So I guess i'm missing some pretty basic knowledge with WPF but this part of it seems to have a rather steep learning curve so maybe a nudge in the right direction of some example code would be good. It seems that most code involves a lot of creation of dataviews or notifying datatypes or at least binding to local objects rather than straight from a query.

+2  A: 

Try instead:

listView.ItemsSource = (from person in People select person).ToList();

[DataContext sets the binding context for the control and its children. ItemsSource sets the collection used to generate the content of the items in the control.]

You could also simply:

listView.ItemsSource = People;

Fuller example:

MainWindow.xaml:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListView x:Name="listView">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Age}"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System.Windows;

namespace WpfApplication2
{
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();

      var people = new[] { new { Name = "John", Age = 40 }, new { Name = "Bill", Age = 50 } };
      listView.ItemsSource = people;
    }
  }
}
Wayne
Thanks, I have tried both DataContext and ItemsSource to no avail. I think my corresponding XAML is the problem. For your first answer, what would you set the DisplayMemberBinding to of the columns?
James Hulse
DisplayMemberBinding should be set to the property of your Person(?) class you want to show in that column.
Wayne
Is my syntax correct as listed in my question: {Binding Name} etc? Because that really doesn't seem to be working for me. I can post a more complete version tonight.
James Hulse
I updated the answer with a full example. Here I'm using an anonymous type for Person, but if your Person has a public Name property, it should work similarly.
Wayne
It occurred to me that maybe your query is returning no results?
Wayne