Kamil Solecki Kamil Solecki - 8 days ago 4
C# Question

C# WPF Grid Columns misinterpreted

I've started developing a new application in WPF C#. The problem I'm having is regarding grid column definitions.

I have divided my Window into separate sections, using Grids' row and col definitions (see code below).

I have two rows. First is currently empty, second one contains a new grid, that is further divided into columns.
All grids are inside a border.

The weird behavior I'm getting, is this section of the code:

<Border BorderThickness="1" BorderBrush="#ffcd22" Grid.Column="1">
<Grid>

</Grid>
</Border>
<Border BorderThickness="1" BorderBrush="#ffcd22" Grid.Column="2">
<Grid>

</Grid>
</Border>
<Border BorderThickness="1" BorderBrush="#ffcd22" Grid.Column="3">
<Grid>

</Grid>
</Border>



The problem is, that the first "subgrid" actually corresponds to the
second column, The second and third both refer to the third column.
In other words, whenever I put any kind of control in the second subgrid (the one which has Grid.Column="2"), the control will appear in the third column for some reason.


I've been fiddling around with it, and can't seem to understand the behavior I'm getting.

Another example: I've put a control in the second column as following:

<Border BorderThickness="1" BorderBrush="#ffcd22" Grid.Column="2">
<Grid>
<TextBox Width="100" Height="50"></TextBox>
</Grid>
</Border>


The image below represents what I got:
enter image description here

Whole XAML code:

<Border BorderThickness="1" BorderBrush="#ffcd22" Margin="10,10,10,10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border BorderThickness="1" BorderBrush="#ffcd22" Margin="-1,-1,-1,-1" Grid.Row="2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Border BorderThickness="1" BorderBrush="#ffcd22" Grid.Column="1">
<Grid>

</Grid>
</Border>
<Border BorderThickness="1" BorderBrush="#ffcd22" Grid.Column="2">
<Grid>

</Grid>
</Border>
<Border BorderThickness="1" BorderBrush="#ffcd22" Grid.Column="3">
<Grid>

</Grid>
</Border>
</Grid>
</Border>
</Grid>

Answer

The problem is that the column numeration starts from 0. You should change your code like this:

<Border BorderThickness="1" BorderBrush="#ffcd22"  Grid.Column="0">
    <Grid>

    </Grid>
</Border>
<Border BorderThickness="1" BorderBrush="#ffcd22"  Grid.Column="1">
    <Grid>

    </Grid>
</Border>
<Border BorderThickness="1" BorderBrush="#ffcd22"  Grid.Column="2">
    <Grid>

    </Grid>
</Border>
Comments