wpfgridmarginuielement

How to make margin be relative to the center of the UIElement and not its top-left corner in a Grid?


I'd like the Margin property to reference the center of the UIElement and not the top-left corner. That way when I change the width/height of the UIElement it stays in the same spot.

Is there a way to configure this behavior or I'll have to rely on Binding to make the adjustment ?

Thanks.

For instance if I change the Width/Height of the following rectangle, its center will move.

<Grid>
    <Rectangle Fill="#FF991C1C" Width="10" Height="40" HorizontalAlignment="Left" Margin="90,161,0,0" VerticalAlignment="Top"/>
</Grid>

Solution

  • For an obscure reason I couldn't figure out that the Rectangle Alignment should be Center if I wanted the Margin to be relative to the center. This code make my Rectangle behaves like I wanted.

    <Grid>
        <Rectangle Fill="#FF991C1C" Width="10" Height="40" HorizontalAlignment="Center" Margin="90,161,0,0" VerticalAlignment="Center"/>
    </Grid>