The Margin property of UIElement, which is parent class of all WPF controls is used to set the margin of a control. Margin property takes four numbers - Left, Top, Right and Bottom, that is margin to the left top and right bottom.
This example sets Margin of a Button control in XAML at design-time.
- <Button Click="OnClick" Margin="10,20,0,0" Name="btn1">
- Click Me!
- </Button>
This example sets Margin of a Button control in C# code behind at run-time.
- void OnClick(object sender, RoutedEventArgs e)
- {
- Thickness marginThickness = btn1.Margin;
- if(marginThickness.Left == 10)
- {
- btn1.Margin = new Thickness(60);
- }
- else
- {
- btn1.Margin = new Thickness(10);
- }
- }