I am creating WPF DataGrid
columns in my C # code. I want one of the columns to automatically stretch to the width of the DataGrid
. In XAML, I set Width="*"
. How to do this in code?
EDIT
Some of the answers seem to lead me to the right solution, but I feel like I need to clarify what I'm trying to do:
I really get a new class from a DataGrid
. In his constructor, I add four columns:
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 to set the last column width as suggested by user24601:
mdColumn.Width = new DataGridLength(0.5, DataGridLengthUnitType.Star);
But this creates a column that is so wide that I can scroll and scroll for a very long time ... Same problem when I use 0.1
or even smaller values.
It seems to me that somehow I am doing it wrong?
EDIT 2
Well, I may have a problem because I am actually adding this to ScrollViewer
. First I will do some more tests ...
EDIT 3
Well, everything does not work when the DataGrid
in a ScrollViewer
... When I delete the ScrollViewer
, everything works as user24601.
Thorsten dittmar
source share