有没有办法使DataGridView中的每个列都占用总网格的百分比宽度?我目前使用的是固定宽度,但是希望给一个列设为15%宽度,另一个列设为25%宽度等,以便填充100%的表格并随网格一起调整大小。
有没有办法使DataGridView中的每个列都占用总网格的百分比宽度?我目前使用的是固定宽度,但是希望给一个列设为15%宽度,另一个列设为25%宽度等,以便填充100%的表格并随网格一起调整大小。
尝试使用 DataGridViewColumn.FillWeight 属性。基本上,您为每列分配一个权重,列会根据这些权重进行调整大小。MSDN文章不是很好。请参见下面的文章以获得更好的解释 -
试一下这个
private void DgvGrd_SizeChanged(object sender, EventArgs e)
{
dgvGrd.Columns[0].Width = (int)(dgvGrd.Width * 0.2);
dgvGrd.Columns[1].Width = (int)(dgvGrd.Width * 0.2);
dgvGrd.Columns[2].Width = (int)(dgvGrd.Width * 0.4);
dgvGrd.Columns[3].Width = (int)(dgvGrd.Width * 0.2);
// also may be a good idea to set FILL for the last column
// to accomodate the round up in conversions
dgvGrd.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
可以使用值转换器
这个转换器减去了一个参数,但你也可以让它除以一个参数。
<local:WidthConverter x:Key="widthConverter"/>
<GridViewColumn Width="{Binding ElementName=lvCurDocFields, Path=ActualWidth, Converter={StaticResource widthConverter}, ConverterParameter=100}">
[ValueConversion(typeof(double), typeof(double))]
public class WidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// value is the total width available
double otherWidth;
try
{
otherWidth = System.Convert.ToDouble(parameter);
}
catch
{
otherWidth = 100;
}
if (otherWidth < 0) otherWidth = 0;
double width = (double)value - otherWidth;
if (width < 0) width = 0;
return width; // columnsCount;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}