简体   繁体   中英

In XAML how do you place items next to each other in a Grid

Ok Xaml is one of my weak points, so I would really appreciate some help on this...what I am trying to achieve is adding a title, name, surname in a listbox as follow:

Mr. John Doe
Ms. John Doe
Mrs. Jane Doe

this is the xaml I have so far, and the result is the name title and surname are overlapping on top of each other:

<DataTemplate>
                <Grid>
                    <TextBlock Text="{Binding Title}"  Width="60" Height="25" Margin="4" HorizontalAlignment="Left" />
                    <TextBlock Text="{Binding FirstName}" Width="60" HorizontalAlignment="Center" />
                    <TextBlock Text="{Binding LastName}" Width="60" HorizontalAlignment="Right" />

                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*"/>
                        <ColumnDefinition Width="1*"/>
                        <ColumnDefinition Width="1*"/>
                    </Grid.ColumnDefinitions>
                </Grid>
            </DataTemplate>

In each TextBlock you need to set Grid.Column="?" where ? is 0, 1, or 2.

If you don't specify a column (or row), elements will by default go to (0,0).

Use the Grid.Column attribute in the TextBlock . Ie:

<TextBlock Text="{Binding Title}"  Width="60" Height="25" Margin="4" HorizontalAlignment="Left" Grid.Column="0"/> 
<TextBlock Text="{Binding FirstName}" Width="60" HorizontalAlignment="Center" Grid.Column="1" /> 
<TextBlock Text="{Binding LastName}" Width="60" HorizontalAlignment="Right" Grid.Column="2" /> 

For each element in the grid, if you want them in an explicit Row or Column, you must specify them. To do this you would use Grid.Row="X" or Grid.Column="X" . If you leave these off, the default value is 0.

In your case, you would want to do the following.

<DataTemplate>
    <Grid>
        <TextBlock Text="{Binding Title}"  Width="60" Height="25" Margin="4" HorizontalAlignment="Left" Grid.Column="0" />
        <TextBlock Text="{Binding FirstName}" Width="60" HorizontalAlignment="Center" Grid.Column="1" />
        <TextBlock Text="{Binding LastName}" Width="60" HorizontalAlignment="Right" Grid.Column="2" />

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
    </Grid>
</DataTemplate>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM