tags:

views:

707

answers:

2

Since the canvas requires a Top/Left for placement, if you want to center something, is adding a grid at the proper Canvas.Top with HorizontalAlignment="Center" the best way to do it, or is there a better way?

This snip is a 150X300 canvas, with some content centered in a grid ....

<Canvas Width="150" Height="300">
    <Grid Canvas.Top="75" Width="106" HorizontalAlignment="Center">
     {whatever you want centered}
    </Grid>
</Canvas>
+1  A: 

I'm not sure if this will meet your exact requirement, but if you put both the canvas and the content inside a grid as peers, it will get you a centered result:

<Grid>
    <Canvas Width="150" Height="300"/>
    <Button HorizontalAlignment="Center" VerticalAlignment="Center" Width="106" Content="Click"/>
</Grid>
Guy Starbuck
+2  A: 

Guy's solution works, but you may have to tweak z-order and visibility if you're juggling hit testing.

Another alternative is having the Grid inside the Canvas (as you've specified in your XAML) with the Height/Width set to (or bound to) the Height/Width of the Canvas. Then setting HorizontalAlignment/VerticalAlignment to Center for the contents of your Grid.

micahtan