C# 如何使WPF DataGrid不显示空行

C# 如何使WPF DataGrid不显示空行,c#,wpf,datagrid,C#,Wpf,Datagrid,我试图将DataGrid的ItemSource设置为列表,然后显示该列表的内容 我的XAML看起来像 <Window x:Class="DataGridDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schem

我试图将DataGrid的ItemSource设置为列表,然后显示该列表的内容

我的XAML看起来像

<Window x:Class="DataGridDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DataGridDemo"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid x:Name="aGrid" ItemsSource= "{Binding actorList}" />

</Grid>
</Window>
  namespace A1
{
 public class Actor
{
    Random rand { get; set; }
    String name { get; set; }
    int age { get; set; }


    public Actor()
    {
        name = "Blank Blankerson";
        age = rand.Next(80) + 6;
    }
    public Actor(String n)
    {
        name = n;
        age = rand.Next(80) + 6;
    }
    public Actor(String n, int a)
    {
        age = a;
        name = n;
    }

    public override String ToString()
    {
        return name + "," + age.ToString();
    }
}
每次代码运行时,它都会生成3个空白行,如下所示

我在互联网上找到的每一个教程都说您只需设置dataGrid.ItemSource=List。这在我的两次尝试中只产生了以下错误。这是令人沮丧的,因为我遵循教程,这仍然是我的结果


那么,如何使WPF DataGrid显示列表?

您需要设置
AutoGenerateColumns=“True”
,除非您正在为列定义自己的模板

<DataGrid x:Name="aGrid" AutoGenerateColumns="True" ItemsSource= "{Binding actorList}" />
  • actorList必须是datacontext中的属性,即主窗口

  • 此外,您应该考虑在模型中实现INotifyPropertyChanged


DataGrid要求get和set方法是公共的。我相应地改变了这一点。现在显示。

您希望看到多少行?请注意,
DataGrid
能够显示用于添加、搜索等的几行。也许这就是您看到的。我认为您的DataGrid代码是不够的。您是否尝试过AutoGenerateColumns=“True”?我尝试过将AutoGenerateColumns设置为True,我还添加了3个元素,并看到3个空行。您的数据成员在Actor类中应该是公共的。您不希望rand作为类的属性。它只需要是一个私人领域。Random rand=new Random()我建议您在回答代码中所做更改时加入示例。更一般地说,WPF绑定需要公共属性。不仅仅是数据网格
<DataGrid x:Name="aGrid" AutoGenerateColumns="True" ItemsSource= "{Binding actorList}" />
  InitializeComponent();
  DataContext = this;
  aGrid.ItemsSource = actorList;