Andrey Mazur
Andrey Mazur

Reputation: 560

Align TextBlocks in a ListViewItem

I have a ListView with few TextBlocks in it. I would like to align those textblocks to get columns, but the problem is that content can have different length. Is there any way to set the length of each text block, and if the value is shorter, to add spaces?

<ListView x:Name="InfoBird_ListView" IsItemClickEnabled="False" IsHitTestVisible="False">
<ListView.ItemTemplate>
    <DataTemplate  x:DataType="local:SelectedBirdData">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding dataId}"    Margin = "0,0,0,0" FontSize="16" />
            <TextBlock Text=":"                   Margin = "0" FontSize="16" />
            <TextBlock Text="{Binding latitude}"  Margin = "10,0,0,0" FontSize="16" />
            <TextBlock Text="{Binding longitude}" Margin = "10,0,0,0" FontSize="16" />
            <TextBlock Text="{Binding altitude}"  Margin = "10,0,0,0" FontSize="16" />
            <TextBlock Text="{Binding timeStamp}" Margin = "10,0,0,0" FontSize="16" />
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>
</ListView>

My ListView

Upvotes: 0

Views: 55

Answers (1)

iam.Carrot
iam.Carrot

Reputation: 5276

There are two ways to go about this,

  1. Set a constant Width for all the Textbox's such that they all fit the data.

  2. Use a Grid and Grid.ColumnDefinitions to create a tabular structure such that you can fit the data into columns. Below is the updated `DataTemplate:

    <Grid Margin="5,40">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="21*"/>
            <ColumnDefinition Width="7*"/>
            <ColumnDefinition Width="76*"/>
            <ColumnDefinition Width="87*"/>
            <ColumnDefinition Width="75*"/>
            <ColumnDefinition Width="1224*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding dataId}" Margin = "0,0,0,0" FontSize="16" Grid.Column="0"/>
        <TextBlock Text=":" Margin = "0" FontSize="16" Grid.Column="1"/>
        <TextBlock Text="{Binding latitude}" Margin = "10,0,0,0" FontSize="16" Grid.Column="2"/>
        <TextBlock Text="{Binding longitude}" Margin = "10,0,0,0" FontSize="16" Grid.Column="3"/>
        <TextBlock Text="{Binding altitude}" Margin="10,0,0,0" FontSize="16" Grid.Column="4"/>
        <TextBlock Text="{Binding timeStamp}" Margin = "10,0,0,0" FontSize="16" Grid.Column="5"/>
    </Grid>
    

The 2nd approach is more adaptive to dynamic Window Sizes

Upvotes: 2

Related Questions