Search code examples
c#wpfteleriklabeltextblock

WPF grid formatting issue.


I want to have Grid and two columns, where in one column I have Label in another a TextBox to display a value. But unfortunately my labels and text boxes are displayed one on another. What I am doing wrong? Is it proper and elegant way to display information? maybe you can suggest any other better way of doing it? Thanks!

<StackPanel Grid.Row="0" Grid.Column="2" VerticalAlignment="Stretch">                   
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <telerik:Label Grid.Column="0" Content="Name" Width="203" FontSize="16"/>
        <telerik:Label Grid.Column="0" Content="Title" Width="203" FontSize="16"/>
        <telerik:Label Grid.Column="0" Content="Phone" Width="203" FontSize="16"/>
        <telerik:Label Grid.Column="0" Content="Email" Width="203" FontSize="16"/>
        <telerik:Label Grid.Column="0" Content="Departament" Width="203" FontSize="16"/>

        <TextBlock Grid.Column="1" x:Name="txtFullName" TextWrapping="Wrap" Height="26"/>
        <TextBlock Grid.Column="1" x:Name ="txtTitle" TextWrapping="Wrap" Height="26"/>
        <TextBlock Grid.Column="1" x:Name ="txtPhone" TextWrapping="Wrap" Height="26"/>
        <TextBlock Grid.Column="1" x:Name ="txtEmail" TextWrapping="Wrap" Height="26"/>
        <TextBlock Grid.Column="1" x:Name ="txtDepartment" TextWrapping="Wrap" Height="26"/>

    </Grid>              
</StackPanel>

Solution

  • You need to add Rows to your Grid. Currently, there is only 1 row (since you have no RowDefinitions), so all the items in each column will just stack on top of one another in the single row.

    Grid Rows are added in much the same way you've added your Columns, and then you tell the controls what row they belong to in much the same way as well. You can add rows like the following:

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>  <!-- * is the default width, so not required -->
            <ColumnDefinition/>            <!-- will be the same as above due to default of * -->
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/> <!-- the * height is implied if not present -->
            <RowDefinition Height="Auto"/>  <!-- this will take up only as much space as necessary -->
        </Grid.RowDefinitions>
    
        <TextBox Grid.Column="0" Grid.Row="0" Text="Label 1"/>
        <TextBox Grid.Column="0" Grid.Row="1" Text="Label 2"/>
        <!-- etc... -->
    </Grid>
    

    A Row with a height of * will stretch to fill available space (divided up between all rows with * height) and a row with a height of "Auto" will shrink so that it takes up only the necessary space to display its contents.