Autofit Columns To Content In A Xceed DataGrid

If you are new to xceed datagrid sooner or later you’ll come to this question: How to do it? well, here is a way to do it, maybe is not the best solution, but it works.

public class MyDataGrid : Xceed.Wpf.DataGrid.DataGridControl{private bool RunAutoFit = false;public MyDataGrid () : base(){this.LayoutUpdated += new EventHandler(Grid_LayoutUpdated); }

private void Grid_LayoutUpdated(object sender, EventArgs e) {if (this.RunAutoFit) {AutoFit();this.RunAutoFit = false; }}public void AutoFit() {

foreach (Column col in this.Columns) {double fittedWidth = col.GetFittedWidth(); if (fittedWidth > 0) col.Width = fittedWidth + 2;}}

protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue){UpdateLayout();base.OnItemsSourceChanged(oldValue, newValue);if (this.AutoCreateColumns) this.RunAutoFit = true; }}}

If this is helpful for you, please leave your comment :)

2 Comments

  1. Luc said,

    March 13, 2008 at 3:11 pm

    Very useful, thanks!

  2. hugo said,

    September 24, 2008 at 2:16 pm

    thx very much


Post a Comment