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

在C#(WPF)中如何将一维字节数组转换为5列DataGrid?

问题描述

我已从二进制文件中读取字节数组readData,需要在C# WPF中将其转换为5列的DataGrid,预期效果如下:

position| 0  | 1  | 2  | 3  | 4  |
0       |a[0]|a[1]|a[2]|a[3]|a[4]|
1       |a[5]|a[6]|a[7]|a[8]|a[9]|
...

之前我尝试创建带固定byte属性的Data类,用ListView实现,但这种方式灵活性差,不适合后续扩展(比如调整列数),代码如下:

public class Data
{
    public int position { get; set; }
    public byte _0 { get; set; }
    public byte _1 { get; set; }
    public byte _2 { get; set; }
    public byte _3 { get; set; }
    public byte _4 { get; set; }
    public byte _5 { get; set; }
    public byte _6 { get; set; }
    public byte _7 { get; set; }
    public byte _8 { get; set; }
    public byte _9 { get; set; }
    public byte _A { get; set; }
    public byte _B { get; set; }
    public byte _C { get; set; }
    public byte _D { get; set; }
    public byte _E { get; set; }
    public byte _F { get; set; }
}

现寻求更灵活的实现方案。


解决方案:用DataTable动态生成列并绑定

这种方式无需固定实体类,可通过参数调整列数,完全适配动态需求,步骤如下:

1. 构建DataTable

根据字节数组和指定列数(这里设为5),动态生成表格结构并填充数据:

// 假设readData是已读取的字节数组
byte[] readData = ...;
int columnCount = 5; // 可按需修改列数

DataTable dt = new DataTable();
// 添加position列
dt.Columns.Add("position", typeof(int));
// 添加字节列,列名从0到columnCount-1
for (int i = 0; i < columnCount; i++)
{
    dt.Columns.Add(i.ToString(), typeof(byte));
}

// 填充数据行
int rowCount = (int)Math.Ceiling((double)readData.Length / columnCount);
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
    DataRow row = dt.NewRow();
    row["position"] = rowIndex; // 行号作为position值
    
    for (int colIndex = 0; colIndex < columnCount; colIndex++)
    {
        int byteIndex = rowIndex * columnCount + colIndex;
        // 字节数组长度足够时赋值,否则填充默认值0
        row[colIndex.ToString()] = byteIndex < readData.Length ? readData[byteIndex] : (byte)0;
    }
    
    dt.Rows.Add(row);
}

2. 绑定到DataGrid

在WPF的XAML中定义DataGrid,开启自动列生成:

<DataGrid x:Name="binaryDataGrid" 
          AutoGenerateColumns="True" 
          CanUserAddRows="False"
          CanUserDeleteRows="False"/>

在代码后台设置数据源:

// 放在读取文件后的逻辑中(比如MainWindow构造函数)
binaryDataGrid.ItemsSource = dt.DefaultView;

可选:优化显示格式(十六进制)

如果需要将字节以十六进制格式显示,可通过AutoGeneratingColumn事件处理:

binaryDataGrid.AutoGeneratingColumn += (sender, e) =>
{
    if (e.Column.Header.ToString() != "position")
    {
        // 设置为两位十六进制大写显示
        e.Column.Binding = new Binding(e.PropertyName) { StringFormat = "X2" };
        e.Column.Width = new DataGridLength(50);
    }
    else
    {
        e.Column.Width = new DataGridLength(70);
    }
};

方案优势

固定实体类的方式列数硬编码,后续调整列数需修改类定义并重新编译;而DataTable方案仅需修改columnCount参数即可适配不同列数需求,灵活性拉满,完全满足后续扩展要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 13:21:34