1
votes

Consider this simple Grid:

<Grid x:Name="gridTest" ShowGridLines="True">
    <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
</Grid>

In code-behind, I add this code:

public MainWindow()
{
    InitializeComponent();

    Label labTest = new Label { Content = "Test Label" };
    gridTest.Children.Add(labTest);
}

The result is:
First Example

Note the label is on top left of the grid. Its ok because I dont set the Grid.Col and Grid.Row (using Grid.SetColumn() and Grid.SetRow())

Now, check the next example:

public MainWindow()
{
    InitializeComponent();

    Label labTest = new Label { Content = "Test Label", Height = 30, Width = 70 };
    gridTest.Children.Add(labTest);
}

I simply added a height and width for the label. But the result is: Second Example

Now, the label acts like centralized in the first cell of the grid although I didnt specify Grid rows or cols for the label! My questions:

  1. Why this happens? Is it "by design" or its a bug?
  2. What can I do to the label in the second example to act like in the first, i.e. appears on topmost and leftmost (0,0) location of the grid when added to grid.Children collection?
1

1 Answers

4
votes
  1. It's by design. The label is in fact always centralized in the first cell of the grid. You just don't see it without giving it dimensions because it fills up the entire cell by default, but its content remains left-aligned at all times.

  2. Align the label itself using its VerticalAlignment and HorizontalAlignment attributes:

    Label labTest = new Label
    {
        Content = "Test Label",
        Height = 30,
        Width = 70,
        VerticalAlignment = VerticalAlignment.Top,
        HorizontalAlignment = HorizontalAlignment.Left
    };
    gridTest.Children.Add(labTest);