很难说没有看到
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中,它显示三个空行。因此,当数据源只实现
,而是自动创建列。