How do Margins in WPF work

When you add a control to your WPF container you typcally set the width and height to align it within the window and in relation to other controls. An alternative to this is to set the controls margin in relation to the container. This plays an important role when you want to add GridSplitters and you want the controls to increase in size in relation to the window when it’s maximized.

You set the margin for each control within the controls XAML tags. Here is an example:

[sourcecode language="xml" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
<Button Grid.Column="0" Grid.Row="0"
          HorizontalAlignment="Left"
          VerticalAlignment="Top"
          Name="button1" ToolTip="Execute"
          Margin="1,2,0,0" Width="50"
          Height="30" Click="button1_Click">
[/sourcecode]

image

I had to work with the margin a little to understand the relationship between the 4 values in the Margin property and the container.

The first value means, how far from the left side of the container do I want my control to be?

The second value means , how far from the top of the container do I want my control to be?

The third value means, how far from the right side of the container do I want my control to be?

And finnaly, the fourth value means, how far from the bottom of the container do I want my control to be?

The reason for the XAML portion of the WPF technology is to help seperate the presentation layer from the business logic layer. Sometimes great coders do not excell in the design or creation of user interfaces (presentation layer). The creation of well designed, user engaging GUIs are becoming sophisticated enough that it’s possible to specilize just in this and the WPF concept fits well into this idea.



Leave a Comment

Your email address will not be published.