Autosize Columns XceedDataGrid WPF
Hello Everyone, I know its been a while, but to recent major events in my life i have been caught up. Either way I am back. Today I will show you a very useful and practical solution to autosize the columns in the XceedDataGrid fro wpf.
There is a property in the columns of the grid that returns the best fitted width of the columns. Apparently this would be as simple as calling this function and setting the width of the column to the result of the fucntion; however there a couple of issues to consider. Otherwise, the function would return -1.
- The function must be called after the layout of the grid has been updated. In order to do this we must called it before setting the itemsource of the DataGrid.
Below there is a implementation of custom class that inherits from XceedDataGrid and automatically autosized the columns:
public class XceedAutoFitColumnGrid : Xceed.Wpf.DataGrid.DataGridControl
{
private bool RunAutoFit = false;public XceedAutoFitColumnGrid(): 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;
}
}

Leave a Reply