Mauro Sampietro
Mauro Sampietro

Reputation: 2814

Vertically center a line in wpf

The following code does not seem to center the line vertically; e.g. the stroke thickness do not seem to be taken into account in arranging the line:

<Grid VerticalAlignment="Center" Width="32" Height="32">
    <Line Stretch="None" HorizontalAlignment="Stretch" VerticalAlignment="Center" X2="32"
       Stroke="Black"
       StrokeThickness="{Binding StrokeThickness}" />
</Grid>

What's missing?

Upvotes: 1

Views: 2220

Answers (1)

James Durda
James Durda

Reputation: 645

I think it may have something to do with StrokeThickness not changing the DesiredSize of the Line element but you can work around it:

The Grid can be replaced with a Canvas:

<Canvas VerticalAlignment="Center" Width="32" Height="32">
    <Line Stretch="None" X2="32" Y1="16" Y2="16"
          Stroke="Black"
          StrokeThickness="15" />
</Canvas>

Or, if you need the outer Grid, wrap the Line in a Canvas:

<Grid VerticalAlignment="Center" Width="32" Height="32" >
    <Canvas VerticalAlignment="Center">
        <Line Stretch="None" X2="32" 
               Stroke="Black"
               StrokeThickness="15" />
    </Canvas>
</Grid>

Upvotes: 4

Related Questions