DataGridView列宽度的百分比

10

有没有办法使DataGridView中的每个列都占用总网格的百分比宽度?我目前使用的是固定宽度,但是希望给一个列设为15%宽度,另一个列设为25%宽度等,以便填充100%的表格并随网格一起调整大小。

3个回答

19

5

试一下这个

    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; 
    }

2

可以使用值转换器
这个转换器减去了一个参数,但你也可以让它除以一个参数。

<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();
        }
    }

1
谢谢你提供的示例代码。我相信这会被某些人使用,尽管我发现另一个答案更容易实现。不过还是非常感谢你的帮助! - Brett Powell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接