Grid Use: Margin and Background
This page was last reviewed on Dec 13, 2023.
Dot Net Perls
Grid. A WPF Grid is an organizational control. With it, we arrange controls in clear, professional ways. We avoid small inconsistencies that might make us look incompetent.
Grid notes. Grids are nested in other controls. When dragging controls around on a Grid, Visual Studio will helpfully render red bars to guide their placement.
Margin example. You can specify a margin on the Grid. By default, the Grid has no margin and it expands to fill its container area.
Info You don't need to set the Grid's width or height to fill the container. A margin can make the grid smaller.
Detail The syntax for the margin attribute is important. We specify the left, top, right and bottom margins in that order.
Tip We can also omit some margin numbers. We can use 1, 2, or 4 numbers. It starts from the left, and mirror on the opposite sides.
<Window x:Class="WpfApplication5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid Background="AliceBlue" Margin="10 20 30 40"> </Grid> </Window>
Background. If you leave the Grid transparent, you can change instead the background of the Window underneath it. But you can specify its background with the Background attribute.
Info In the Margin section on this article, I show the AliceBlue background. I used AliceBlue because it is shown first in Visual Studio.
TabControl. Other controls use a nested grid to lay out their controls. Try dragging a TabControl to your grid: this will have a nested grid.
Tip The TabControl uses a gray background color "#FFE5E5E5." This comes out to a light gray color.
And This color can also be adjusted. I suggest the color AliceBlue, which is first in the list.
GridSplitter. A Grid can be used with rows and columns (with RowDefinitions and ColumnDefinitions). And if you use rows and columns, you can use a GridSplitter to resize them.
Note With a GridSplitter, we create adjustable user interfaces. These interfaces are more versatile than ones that cannot resize.
Info In Windows Forms, we have the TableLayoutPanel to organize controls in this way. The Grid serves a similar purpose.
Summary. Controls can be hard to arrange. And if you make a mistake, it will make the entire program look bad. With grid, we arrange controls with help from Visual Studio.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 13, 2023 (grammar).
© 2007-2024 Sam Allen.