Why is the content of pure IEnumerable invisible to the WPF DataGrid?

Say I have a datagrid with an itemsource tied to a Collection property, which, for example, is IEnumerable. Of course, I wrote a suitable getter and setter for this.

Now, when I assign this property (Collection) to just IEnumerable (as the result of some method), for example:

Collection = FooMethod(); // FooMethod returns IEnumerable<MyClass>

datagrid will display empty rows. The number of rows will correspond to the number of collections.

But when I force the conversion, like this:

Collection = FooMethodp().ToArray(); // forced fetching data

datagrid will show all rows with content.

So, what stops a datagrid from displaying data in the event of a pure IEnumerable? He must iterate over the collection, so sampling happens anyway.

edits

For recording only. MyClass:

public class ErrorsIndicators
{
    public double Min { get; set; }
    public double Max { get; set; }
    public double Avg { get; set; }
}

and FooMethod returns (return) several elements. So, nothing out of the ordinary here.

+3
1

, FooMethod(), , -, IEnumerable<T>, - (, ICollection<T> IList<T>). , DataGrid , DataGrid.Columns.

, .

MainWindow.xaml.cs

namespace DataGridTest
{
    using System.Collections.Generic;
    using System.Windows;

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

            Customers = this.GetCustomers();
            DataContext = this;
        }

        private IEnumerable<Customer> GetCustomers()
        {
            yield return new Customer() { Name = "first" };
            yield return new Customer() { Name = "second" };
            yield return new Customer() { Name = "third" };
        }

        public IEnumerable<Customer> Customers
        {
            get;
            set;
        }
    }

    public class Customer
    {
        public string Name
        {
            get;
            set;
        }
    }
}

MainWindow.xaml

<Window x:Class="DataGridTest.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">
    <DataGrid ItemsSource="{Binding Customers}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        </DataGrid.Columns>
    </DataGrid>
</Window>

DataGrid.Columns XAML, . , , , , IEnumerable<T>, .

+5

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


All Articles