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

WPF DataGrid通过ComboBox排序后数据消失问题排查求助

问题排查与解决方法

核心问题

你代码里的SortedTable方法存在关键错误:使用dataHandler.KicksTable.Clone()创建的是空数据表(仅复制表结构,不包含任何数据),后续对这个空表的DataView排序,最终返回的DataTable自然没有数据,导致DataGrid绑定后只显示表头。

修复步骤

1. 修正SortedTable方法的数据复制逻辑

把Clone()替换为Copy(),Copy()会同时复制表的结构和数据:

private DataTable SortedTable(string sortingBy)
{
    // 用Copy()替代Clone(),保留原表数据
    DataView sortedTable = dataHandler.KicksTable.Copy().DefaultView;

    switch (sortingBy)
    {
        case "Type":
            sortedTable.Sort = "Type";
            break;
        case "Size, ascending":
            sortedTable.Sort = "Size asc";
            break;
        // 可添加默认排序逻辑,避免未匹配到选项时返回无序数据
        default:
            sortedTable.Sort = "YourDefaultColumn";
            break;
    }

    return sortedTable.ToTable();
}

2. 可选优化:避免列可见性设置时的索引越界

重新绑定ItemSource后,DataGrid的列集合可能会重新生成(如果AutoGenerateColumns为True),建议在设置列可见性前,先确保propertiesHandler.TablePropertiesIndex中的索引值在当前列集合的有效范围内:

private void DbFilterSortByBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (DbFilterSortByBox.SelectedItem != null)
    {
        DbMainTable.ItemsSource = SortedTable(DbFilterSortByBox.SelectedItem.ToString()).DefaultView;

        // 先检查索引有效性,避免索引越界异常
        for (int i = 0; i < propertiesHandler.TablePropertiesIndex.Length; i++)
        {
            int columnIndex = propertiesHandler.TablePropertiesIndex[i];
            if (columnIndex >= 0 && columnIndex < DbMainTable.Columns.Count && !propertiesHandler.TablePropertiesValue[i])
            {
                DbMainTable.Columns[columnIndex].Visibility = Visibility.Hidden;
            }
        }
    }
}

额外说明

  • 如果你的DataGrid是手动定义列(AutoGenerateColumns=False),那列索引的对应关系更稳定,但仍建议添加索引有效性检查。
  • 若需要支持降序排序,只需在Sort语句中指定desc,比如"Size desc"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:30:49