我在WPF中有一个自动生成列的数据网格。有些列的宽度超过整个屏幕,我想检查宽度,如果超过500,则将其设置为500,但如果小于500则保持当前宽度。
<DataGrid x:Name="dgLM" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding}" HorizontalAlignment="Stretch"
Margin="5" VerticalAlignment="Stretch" IsReadOnly="True" CanUserAddRows="False" AutoGenerateColumns="True" CanUserDeleteRows="False"
LoadingRow="dg_LoadingRow" AlternatingRowBackground="#FFDAD5D5"
AutoGeneratingColumn="dgMain_AutoGeneratingColumn" >
<!--<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="DarkGray"/>
</DataGrid.Resources>-->
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="DarkGray" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
</DataGrid>
,代码是:
private void dgMain_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(System.DateTime))
(e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy HH:mm:ss";
//e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
if (e.Column.Width > 500)
{
e.Column.Width = 500;
}
}
感谢任何帮助!
答案 0 :(得分:0)
在AutoGeneratingColumn中处理列宽时,应使用DataGridLength。
您也可以更改为双倍的e.Column.MaxWidth。