...">

WPF DataGrid is populated unless I use LINQ to filter my items

I have a simple WPFToolkit DataGrid:

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

And in the code behind the simple class Contact:

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 the code behind, I create a collection Listand bind it to mine 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 this works fine, but if I filter these contacts with LINQ as follows:

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 mine is DataGridfilled, but all fields are empty (!). For example, in the above case, my DataGridhas three lines, all of which are empty. Strange when debugging filteredContactscontains four elements.

How can I use LINQ to filter my custom objects and make them appear in mine DataGrid?

0
1

:

  • theDataGrid.ItemsSource = filteredContacts;
    

    to

    theDataGrid.ItemsSource = filteredContacts.ToList();
    
  • View .

    ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(contacts);
    
    view.Filter = delegate(object item) { return (item as Contact).LastName.StartsWith("T"); };
    
    theDataGrid.ItemsSource = view;
    
+3

Source: https://habr.com/ru/post/1702479/


All Articles