简体   繁体   中英

WPF - Center control (label) within Canvas

Greetings

I'm trying to fix the positioning of controls in my WPF Application. In my application I have several Labels which each are in a different Canvas. I'm trying to center the label within the canvas. The code I currently have for one Label is the following:

<Canvas Height="42" HorizontalAlignment="Left" Margin="0,1,0,0" Name="canvasPlayer1" VerticalAlignment="Top" Width="172" >
    <Label Content="" Foreground="White" FontSize="15" FontFamily="Eurostile LT ExtendedTwo" Height="Auto" HorizontalAlignment="Center" Margin="0,5,0,0" Name="labelPlayer1Name" VerticalAlignment="Center" Width="Auto" />
</Canvas>

Now for starters the problem with this is that it does not center the text at all, it stays at the original position. What I'm trying to achieve is to center the content of the label in that canvas BUT it cannot exceed the width of the canvas.

Helpful suggestions are welcomed! If you have any comments regarding my thinking pattern to solve this issue please do notify me as well!

Thank you in advance

You shouldn't use Canvas for this. Alignment properties and margins will have no effect on elements laid out in a Canvas. What you should use instead is a Grid. Canvas is not particularly useful for most layout scenarios.

<Grid Height="42" HorizontalAlignment="Left" Margin="0,1,0,0" 
      Name="canvasPlayer1" VerticalAlignment="Top" Width="172" >
    <Label Content="" Foreground="White" FontSize="15" 
           FontFamily="Eurostile LT ExtendedTwo" 
           HorizontalAlignment="Center" Margin="0,5,0,0" 
           Name="labelPlayer1Name" VerticalAlignment="Center" />
</Grid>

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