代码之家  ›  专栏  ›  技术社区  ›  greenoldman

为什么纯IEnumerable的内容对于WPF DataGrid是不可见的?

  •  3
  • greenoldman  · 技术社区  · 15 年前

    现在,当我将IEnumerable(作为某个方法的结果)赋给这个属性(集合)时,如下所示:

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

    datagrid将显示空行。行的计数将与集合的计数匹配。

    但当我强制转换时,就像这样:

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

    datagrid现在将显示包含内容的所有行。

    记录在案。我的班级是这样的:

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

    1 回复  |  直到 5 年前
        1
  •  5
  •   Tim Cooper    14 年前

    很难说没有看到 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;
            }
        }
    }
    

    主窗口.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>
    

    如果你移除 在XAML中,它显示三个空行。因此,当数据源只实现 ,而是自动创建列。

    推荐文章