greenoldman
greenoldman

Reputation: 21082

How to get internal view width of WPF DataGrid?

Let's say you have DataGrid (standard) with width = 100 pixels, but you have such wide columns (and so many), that you have to scroll the DataGrid horizontally (entire DataGrid, not individual columns) to read the content.

+--------+ 
|very lon|
|<#=====>|
+--------+

I hope you get the picture. Ok, as I said, the DataGrid width is 100 pixels, but how to get the width of view of DataGrid -- obviously it is bigger than DataGrid?

Edit 1

I traversed visual tree of DataGrid to get ScrollViewer of it. Next I read ExtentWidth -- this value is however a bit too small. If I add RowHeaderActualWidth of DataGrid the sum is on the other hand too big. So, there has to be another factor (or completely better, more reliable, way to read internal width of the DataGrid view).

Upvotes: 0

Views: 2211

Answers (3)

Andrew Rollings
Andrew Rollings

Reputation: 14571

In Xaml you can just use, e.g.

Width="{Binding ElementName=DatagridName, Path=CellsPanelActualWidth}" 

Upvotes: 1

exnihilo1031
exnihilo1031

Reputation: 175

I dont know if its too late to answer, but for general knowledge you can get it with

//in your class declaration
DataGrid gridInstance;

//in your method
Type type = typeof(DataGrid);
PropertyInfo pInfo = type.GetProperty("CellsPanelActualWidth", BindingFlags.NonPublic | BindingFlags.Instance);
double actualWpfWidth = (double)pInfo.GetValue(gridInstance, null);

Upvotes: 2

Wonko the Sane
Wonko the Sane

Reputation: 10823

I don't have 4.0 available in front of me at the moment, but I would guess that you could do something like this:

private Double GetGridWidth(DataGrid grid)
{
    Double width = 0.0;
    foreach (DataGridColumn column in myDataGrid.Columns)
    {
        width += column.ActualWidth;
    }

    return width;
}

or, using LINQ:

private Double GetGridWidth(DataGrid grid)
{
    return grid.Columns.Sum(col => col.ActualWidth);
}

Upvotes: 1

Related Questions