You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF DataGrid绑定TableData数据后显示空白行求助

WPF DataGrid显示空行问题排查

问题重现

定义TableData类:

public class TableData
{
    public string ID, WrestlerID;
    public string Name;
}

创建数据列表并添加项:

List<TableData> _tableData = new List<TableData>();
TableData tableData = new TableData
{
    ID = "0",
    WrestlerID = "000",
    Name = "test1"
};
_tableData.Add(tableData);
TableData tableData2 = new TableData
{
    ID = "1",
    WrestlerID = "111",
    Name = "test2"
};
_tableData.Add(tableData2);

将数据添加到DataGrid:

foreach (TableData data1 in _tableData)
{
    DGTable.Items.Add(data1);
}

DataGrid的XAML配置:

<DataGrid x:Name="DGTable" Grid.Row="1">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="100"/>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/>
        <DataGridTextColumn Header="Wrestler ID" Binding="{Binding WrestlerID}" Width="200"/>
    </DataGrid.Columns>
</DataGrid>

运行后DataGrid显示2行,但所有字段内容为空。

原因分析

WPF的数据绑定机制默认仅支持绑定到公共属性(Properties),而你定义的TableData类中的ID、WrestlerID、Name都是公共字段(Fields),并非属性。DataGrid的Binding无法识别并访问字段值,因此出现空行现象。

解决方法

将TableData类中的字段修改为带get/set访问器的公共属性:

public class TableData
{
    public string ID { get; set; }
    public string WrestlerID { get; set; }
    public string Name { get; set; }
}

额外优化建议

WPF中更简洁的方式是直接将数据列表设置为DataGrid的ItemsSource,无需逐个添加项:

DGTable.ItemsSource = _tableData;

内容的提问来源于stack exchange,提问作者DC37

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 02:15:22