ADi
ADi

Reputation: 219

WPF Datagrid size stretching issue

i have mainGrid containing scrollviwer containing stackPanelContent.

I ham adding a grid with two columns, each containing a DataGrid. The problem is DataGrid1 is empty and DataGrid2 contains data. But My DataGrid1 is also expanding in height with respect to DataGrid2. Why such behavior?

enter image description here

Here is the code:

var datagridDetails = new DataGrid { IsReadOnly = true, AutoGenerateColumns = false };
var columnDetails = new DataGridTextColumn
{
    Header = "Details",
    MinWidth = 400,
    Width = StackPanelContent.ActualWidth/2 - 8,
    CanUserSort = false,
    CanUserResize = false
};
datagridDetails.Columns.Add(columnDetails);

var datagridTopic = new DataGrid { IsReadOnly = true, AutoGenerateColumns = false};
var columnTopic = new DataGridTextColumn
{
    Header = "Topic",
    MinWidth = 400,
    Width = StackPanelContent.ActualWidth/2 - 8,
    CanUserSort = false,
    CanUserResize = false,
    Binding = new Binding("Title")
};
datagridTopic.Columns.Add(columnTopic);
datagridTopic.ItemsSource = topics;

var myGrid = new Grid();
var col1 = new ColumnDefinition();
var col2 = new ColumnDefinition();
myGrid.ColumnDefinitions.Add(col1);
myGrid.ColumnDefinitions.Add(col2);
StackPanelContent.Children.Add(myGrid);

Grid.SetColumn(datagridDetails, 0);
myGrid.Children.Add(datagridDetails);

Grid.SetColumn(datagridTopic, 1);
myGrid.Children.Add(datagridTopic);

Upvotes: 0

Views: 254

Answers (2)

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

You should change VerticalAlignment for DataGrid to be Top instead of Stretch.


Why that happened?

Keep in mind that on a vertically aligned StackPanel all child controls get stretched horizontally. On the other hand horizontally aligned StackPanel - vertically stretch child elements. StackPanel does this by setting the corresponding property on its child controls to Stretch.

MSDN

Upvotes: 3

Nitin Joshi
Nitin Joshi

Reputation: 1668

Declare data grid as follow:

var datagridDetails = new DataGrid { IsReadOnly = true, AutoGenerateColumns = false, VerticalAlignment = VerticalAlignment.Top};

Upvotes: 1

Related Questions