Skip to content

Instantly share code, notes, and snippets.

@rockhymas
Created June 23, 2012 13:57
Show Gist options
  • Save rockhymas/2978368 to your computer and use it in GitHub Desktop.
Save rockhymas/2978368 to your computer and use it in GitHub Desktop.
WeightColumns
public void WeightColumns(List<int> weights, List<int> fixedWidths)
{
if (TableStyles.Count <= 0) return;
var tableStyle = TableStyles[0];
if (tableStyle.GridColumnStyles.Count < 1) return;
if (fixedWidths == null)
fixedWidths = Enumerable.Repeat(0, tableStyle.GridColumnStyles.Count).ToList();
if (weights == null)
weights = Enumerable.Repeat(1, tableStyle.GridColumnStyles.Count).ToList();
if (tableStyle.GridColumnStyles.Count != weights.Count)
throw new Exception("Wrong number of weights for weighted column resizing");
if (tableStyle.GridColumnStyles.Count != fixedWidths.Count)
throw new Exception("Wrong number of fixedWidths for weighted column resizing");
var verticalScrollBar = GetVScrollBar();
var verticalScrollBarWidth = verticalScrollBar != null ? verticalScrollBar.Width : 0;
SetColumnWidths(weights, fixedWidths, verticalScrollBarWidth, tableStyle);
// Resize columns if that got rid of the vertical scrollbar
if (verticalScrollBar != null && !verticalScrollBar.Visible)
SetColumnWidths(weights, fixedWidths, 0, tableStyle);
}
private void SetColumnWidths(List<int> weights, List<int> fixedWidths, int verticalScrollBarWidth, DataGridTableStyle tableStyle)
{
var columnDividerCount = columnDividersCalculator(tableStyle.GridColumnStyles.Count);
var usableWidth = (int) (ClientSize.Width
- verticalScrollBarWidth
- BorderWidth * 2 * DpiMultiple
- ColumnDividerWidth * columnDividerCount * DpiMultiple
- fixedWidths.Sum());
var totalWeight = weights.Sum();
var fixedWidthIndex = 0;
var columnWidths = weights.Select(x =>
(int) (usableWidth*((float) x/totalWeight)) + fixedWidths[fixedWidthIndex++]
).ToList();
var extraWidth = usableWidth + fixedWidths.Sum() - columnWidths.Sum();
for (var index = 0; index < tableStyle.GridColumnStyles.Count; index++)
tableStyle.GridColumnStyles[index].Width = columnWidths[index] + (index < extraWidth ? 1 : 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment