WPF Datagrid大小拉伸问题

时间:2014-01-16 13:39:32

标签: c# wpf datagrid

我的mainGrid包含scrollviwer,其中包含stackPanelContent

我添加一个包含两列的网格,每列包含一个DataGrid。问题是DataGrid1为空,DataGrid2包含数据。但是我的DataGrid1相对于DataGrid2也在扩展。为什么会这样?

enter image description here

以下是代码:

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);

2 个答案:

答案 0 :(得分:3)

您应该将DataGrid的{​​{3}}更改为Top而不是Stretch


为什么会这样?

请注意,在垂直对齐的StackPanel所有子控件上,水平拉伸。另一方面,水平对齐StackPanel - 垂直拉伸子元素。 StackPanel通过将其子控件的相应属性设置为Stretch来完成此操作。

VerticalAlignment

答案 1 :(得分:1)

声明数据网格如下:

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