WPF 用DateGrid 显示内存表格DataTable,显示内容不完整

 private void ShowDataTable(DataTable table)
        {
            if (table == null) return;
            DataGrid dg = new();
            dg.CanUserAddRows = false;
            dg.ItemsSource = table.DefaultView;
            dg.GridLinesVisibility = DataGridGridLinesVisibility.All;
          //MainSheld是View中的一个StackPanel容器
            this.MainSheld.Children.Add(dg);
        }

表格内容为,所有列的数据类型均为string:

img


但显示的效果如下

img

前面两列没有显示, 问题出在哪里?

当你在使用WPF的DataGrid显示内存表格DataTable时,如果发现显示内容不完整,可能是由于行高、列宽或自动调整设置导致的。你可以尝试以下方法解决此问题:

  1. 设置行高:
    如果你的行高不够,可能会导致内容显示不完整。通过设置RowHeight属性,可以确保每行都有足够的高度来显示内容。例如:

    <DataGrid x:Name="dataGrid" RowHeight="25">
        <!-- 其他代码 -->
    </DataGrid>
    
  2. 设置列宽:
    如果列宽不足,某些内容可能会被截断。可以通过设置ColumnWidth属性,为每列分配足够的宽度。例如:

    <DataGrid x:Name="dataGrid" ColumnWidth="SizeToHeader">
        <!-- 其他代码 -->
    </DataGrid>
    
  3. 自动调整列宽:
    如果列的内容长度不定,你可能需要让列宽自适应。可以通过设置AutoGenerateColumns属性为True,并设置列宽调整模式为SizeToHeader或Fill。例如:

    <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" ColumnWidth="SizeToHeader">
        <!-- 其他代码 -->
    </DataGrid>
    
  4. 设置数据表格样式:
    如果你想自定义DataGrid的样式,可以通过编写样式代码来实现。例如:

    <DataGrid x:Name="dataGrid" AutoGenerateColumns="True" ColumnWidth="SizeToHeader">
        <DataGrid.Resources>
            <Style TargetType="DataGridCell">
                <Setter Property="HorizontalAlignment" Value="Center" />
                <Setter Property="VerticalAlignment" Value="Center" />
            </Style>
        </DataGrid.Resources>
    </DataGrid>
    
  5. 确保DataTable数据完整:
    最后,请检查DataTable中的数据是否完整。如果数据不完整或被截断,DataGrid也无法显示完整的内容。

尝试以上方法,应该可以帮助你解决WPF DataGrid显示内存表格DataTable时内容不完整的问题。