Content alignment in label WPF

24,165

Solution 1

If you use Snoop WPF to examine your running application you will find that the Labels Visual Tree includes a Border element width a padding of 5,5,5,5.

If you remove the padding using SnoopWPF everything renders fine. This indicates that whilst the label width is 223 the width for the text content is less and its stretching into this padding on the longer text. Try making the label slightly wider or just using a TextBlock instead.

Solution 2

<GroupBox Header="Normal" Width="450" Height="150" Name="grpNormal">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Label Grid.Row="0" Name="lblStartRegNormal" Width="223" Content="Enter the starting reg number: " FontSize="16" HorizontalContentAlignment="Right" />
            <TextBox Name="txtStartRegNormal" Grid.Column="1" Height="40" Width="200"/>
            <Label Grid.Row="1"  Name="lblEndRegNormal" Width="223" Content="Enter the ending reg number: " FontSize="16" HorizontalContentAlignment="Right"/>
            <TextBox Name="txtEndRegNormal" Height="40" Grid.Row="1" Grid.Column="1" Width="200" />
        </Grid>
    </GroupBox>

It looks like this:

enter image description here

Share:
24,165
Nithin Nayagam
Author by

Nithin Nayagam

Updated on July 09, 2022

Comments

  • Nithin Nayagam
    Nithin Nayagam almost 2 years

    i have a small problem with the alignment of my text in a label

    this is my xaml code

    <GroupBox Header="Normal" Width="450" Height="150" Name="grpNormal">
        <Canvas Name="cvsNormal" Width="440" Height="140">
            <Label Name="lblStartRegNormal" Width="223" Content="Enter the starting reg number: " FontSize="16" Canvas.Left="2" Canvas.Top="15" HorizontalContentAlignment="Right" />
            <TextBox Name="txtStartRegNormal" Height="40" Width="200" Canvas.Right="10" Canvas.Top="15"/>
            <Label Name="lblEndRegNormal" Width="223" Content="Enter the ending reg number: " FontSize="16" Canvas.Left="5" Canvas.Top="65" HorizontalContentAlignment="Right"/>
            <TextBox Name="txtEndRegNormal" Height="40" Width="200" Canvas.Right="10" Canvas.Top="65"/>
        </Canvas>
    </GroupBox>
    

    here is the output

    enter image description here

    but when i change my label content, the colons on the right side are not aligned

    enter image description here

    What am i doing wrong here?

  • Nithin Nayagam
    Nithin Nayagam almost 11 years
    That worked great. I just had to increase the width of the label.