tags:

views:

1529

answers:

1

I've got a simple WPFToolkit DataGrid:

<Grid>
    <dg:DataGrid Name="theDataGrid"/>
</Grid>

And in code behind a simple Contact class:

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Contact(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
}

in my main constructor in code behind I build a List collection and bind it to my DataGrid:

List<Contact> contacts = new List<Contact>();
contacts.Add(new Contact("John", "Tester"));
contacts.Add(new Contact("Jill", "Tester"));
contacts.Add(new Contact("Joe", "Tester"));
contacts.Add(new Contact("Jimmy", "Nontester"));
theDataGrid.ItemsSource = contacts;

and that works fine, but if I filter these contacts with LINQ like this:

List<Contact> contacts = new List<Contact>();
contacts.Add(new Contact("John", "Tester"));
contacts.Add(new Contact("Jill", "Tester"));
contacts.Add(new Contact("Joe", "Tester"));
contacts.Add(new Contact("Jimmy", "Nontester"));

var filteredContacts = contacts.Where(contact => contact.LastName.StartsWith("T"));
theDataGrid.ItemsSource = filteredContacts;

Then my DataGrid is populated, but the fields are all empty (!). For example, in the above case, my DataGrid has three rows which are all empty. Strangely when debugging, filteredContacts contains four items.

How can I use LINQ to filter my custom objects AND get them to display in my DataGrid?

+2  A: 

Well im not sure but i would try two things.

1) change theDataGrid.ItemsSource = filteredContacts; to theDataGrid.ItemsSource = filteredContacts.ToList();

2) the second would be to use a View and filter on the view.

ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(contacts);

view.Filter = delegate(object item) { return (item as Contact).LastName.StartsWith("T"); };

theDataGrid.ItemsSource = view;

Eric

Your first suggestion worked perfectly, thanks! :-)
Edward Tanguay