Search code examples
xamlwindows-store-appsuielement

How is the margin of a UIElement calculated


For the xml below

<Image Width="30px" Height="30px" Margin="1 1 1 1" />

The margin is 1 1 1 1 but the image is at the centre of the screen (668 369 668 369). Why is this happening? Isn't the margin above invalid? Also, for the position of anything, you just need margin left and margin top. That's how winforms works, right? I don't understand why the Thickness constructer requires 4 values.


Solution

  • A Thickness for a Margin is how many pixels from each edge of the element. These are Left, Top, Right, and Bottom.

    Here's an example:

    Margin="10,15,5,0"
    

    The code above defines a margin of:

    • 10 Pixels from the Left.
    • 15 Pixels from the Top.
    • 5 Pixels from the Right.
    • 0 Pixels from the Bottom.

    The margin is always defined as Left, Top, Right, Bottom. However there are some shortcuts.

    For example:

    Margin="10,15"
    

    The margin here will be defines as:

    • 10 Pixels on the Left and Right.
    • 15 Pixels on the Top and Bottom.

    And also:

    Margin="15"
    

    This margin will be 15 pixels on all sides.

    To answer your question more directly, you are simply missing the commas.