Sabtu, 17 Agustus 2013

Margin and Padding of Elements: WPF

In our previous post we have set Height and Width properties of an element, now we will set the next size related properties i.e. Margin and Padding. Margin controls how much extra space gets placed around the outside edges of the element, whereas padding controls around the inside edges of the element.

Margin and Padding can be assign in following simple ways:
  • Margin = "10", same margin of all four sides.
  • Margin = "10,5", 10 for left & right, 5 for top & bottom.
  • Margin = "10,5,10,5", for left, top, right and bottom respectively.
Same can be used for padding. Here is xaml code with three buttons having some margins.
<StackPanel Orientation="Horizontal">
<Button Margin="10">Button 1</Button>
<Button Margin="20,5">Button 2</Button>
<Button Margin="20,15,20,15">Button 3</Button>
</StackPanel>
As padding controls around the inside edges of the element, I have used a border across each button:
<StackPanel Orientation="Horizontal" Height="60">
<Border Background="Aqua" BorderThickness="2">
<Button Padding="10">Button 1</Button>
</Border>
<Border Background="Aqua">
<Button Padding="10,15">Button 2</Button>
</Border>
<Border Background="Aqua">
<Button Padding="20,15,20,15">Button 3</Button>
</Border>
</StackPanel>
The effect of padding will look like in the following screenshot:

Margin and Padding of Elements in WPF

Varying the values of these margins and paddings, we can measure the changes. If one want to use all these margins through code behind then we have to use Thickness class like the below code:
Button button1 = new Button();
button1.Margin = new Thickness(10);
button1.Margin = new Thickness(20, 15, 20, 15);

As we can see that either we can use a single value or all the four values to use margin property of an element. There is no option to use the second type i.e. the one for left & right and one for top & bottom.

Alignments and Height & Width

Tidak ada komentar:

Posting Komentar