你有一些选择。您可以将 设置DataGrid.ColumnWidth
为固定宽度或DataGridLength.SizeToHeader
:
对于所有列:
<DataGrid ColumnWidth="{x:Static DataGridLength.SizeToHeader}" />
对于单个列:
<DataGridTextColumn Width="{x:Static DataGridLength.SizeToHeader}" />
此外,您可以在单元格内容中添加省略号,以向用户指示单元格内容溢出。
自动生成列时:
<DataGrid AutoGeneratingColumn="OnDataGrid_AutoGeneratingColumn"
ColumnWidth="{x:Static DataGridLength.SizeToHeader}">
<DataGrid.Resources>
<Style x:Key="DataGridTextColumnEditStyle"
TargetType="{x:Type TextBlock}"
BasedOn="{StaticResource {x:Type TextBlock}}">
<Setter Property="TextTrimming"
Value="CharacterEllipsis" />
</Style>
</DataGrid.Resources>
</DataGrid>
private void OnDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.Column is DataGridTextColumn textColumn)
{
var dataGrid = sender as DataGrid;
var textColumnEditStyle = dataGrid.FindResource("DataGridTextColumnEditStyle") as Style;
textColumn.ElementStyle = textColumnEditStyle;
}
}
明确定义列时:
<DataGrid AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Width="{x:Static DataGridLength.SizeToHeader}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}"
BasedOn="{StaticResource {x:Type TextBlock}}">
<Setter Property="TextTrimming"
Value="CharacterEllipsis" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
另一种解决方案是允许DataGrid
计算宽度并在之后验证和强制每个列宽:
<DataGrid Loaded="OnDataGrid_Loaded" />
private const double MaxColumnWidth = 200;
private void OnDataGrid_Loaded(object sender, RoutedEventArgs e)
{
var dataGrid = sender as DataGrid;
// Alternatively, select the particular column of interest by index or Header value
foreach (DataGridColumn column in dataGrid.Columns)
{
if (column.ActualWidth > MaxColumnWidth)
{
column.Width = MaxColumnWidth;
}
}
}