Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make DataGrid column stretch from C# code?

Tags:

c#

wpf

datagrid

I'm creating the columns of a WPF DataGrid in my C# code. I want one of the columns to stretch to the width of the DataGrid automatically. In XAML, I'd set Width="*". How do I do it in code?

EDIT
Some of the answers seem to lead me to the right solution, but I feel I need to elaborate a bit more what I'm trying to do:

I'm actually deriving a new class from DataGrid. In its constructor, I add four columns like that:

this.IsReadOnly = true;
this.AutoGenerateColumns = false;
this.ItemsSource = m_dataSource;

DataGridTextColumn anColumn = new DataGridTextColumn() { Header = "Col1", Binding = new Binding("B1") };
DataGridTextColumn tpColumn = new DataGridTextColumn() { Header = "Col2", Binding = new Binding("B2") };
DataGridTextColumn txColumn = new DataGridTextColumn() { Header = "Col3", Binding = new Binding("B3") };
DataGridTextColumn mdColumn = new DataGridTextColumn() { Header = "Col4", Binding = new Binding("B4") };

this.Columns.Add(anColumn);
this.Columns.Add(tpColumn);
this.Columns.Add(txColumn);
this.Columns.Add(mdColumn);

I tried setting the last column's width like user24601 suggested:

mdColumn.Width = new DataGridLength(0.5, DataGridLengthUnitType.Star);

But this creates a column that is so wide I can scroll and scroll for a very long time... Same problem when I use 0.1 or even smaller values.

I seems to me I'm doing it in the wrong place somehow?

EDIT 2
OK, I may have the problem because I'm actually adding this to a ScrollViewer. I'll run some further tests first...

EDIT 3
Well, things don't work when having the DataGrid within a ScrollViewer... When I remove the ScrollViewer, things work like user24601 said.

like image 484
Thorsten Dittmar Avatar asked Jan 24 '12 14:01

Thorsten Dittmar


1 Answers

You're actually using something called a DataGridLength there.

Try something like this:

Grid.ColumnDefinitions[0].Width = new DataGridLength(0.2, DataGridLengthUnitType.Star);
Grid.ColumnDefinitions[1].Width = new DataGridLength(0.8, DataGridLengthUnitType.Star);

That will split the remaining space 80% / 20% between these two columns.

like image 195
DanTheMan Avatar answered Nov 14 '22 13:11

DanTheMan