WPF WrapPanel and Grid layout, wpfwrappanelgrid
When designing the client interface, some layout elements often use. Grid StackPanel Canvas WrapPanel and so on.
The following is a case study to illustrate the use cases of Grid and WrapPanel.
1. In the preceding layout, if the number of child elements is unknown, we should use WrapPanel or StackPanel for layout. child elements will wrap their own lines.
2. In each row, the first element must be left, the second element must be centered, and the third element must be left. In this case, you should use the Grid layout, add three columns, and set the horizontal direction for the corresponding elements in each column.
The following code is used:
1. interface:
<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="250" Width="500" Loaded="MainWindow_OnLoaded" WindowStartupLocation="CenterScreen"> <Window.Resources> </Window.Resources> <Grid> <ScrollViewer> <WrapPanel x:Name="MyWrapPanel" Margin="10,0"> </WrapPanel> </ScrollViewer> </Grid></Window>
2. Background (the language is VB. In fact, VB is similar to C)
Class MainWindow Private Sub MainWindow_OnLoaded(sender As Object, e As RoutedEventArgs) Dim grid As Grid Dim index = 0 For i As Integer = 0 To 10 If index Mod 3 = 0 Then grid = New Grid() grid.Width = 440 grid.Margin = New Thickness(0, 20, 0, 20) grid.ColumnDefinitions.Add(New ColumnDefinition()) grid.ColumnDefinitions.Add(New ColumnDefinition()) grid.ColumnDefinitions.Add(New ColumnDefinition()) MyWrapPanel.Children.Add(grid) End If Dim checkBox = New CheckBox() Dim value = index Mod 3 If value = 0 Then checkBox.HorizontalAlignment = HorizontalAlignment.Left ElseIf value = 1 Then checkBox.HorizontalAlignment = HorizontalAlignment.Center ElseIf value = 2 Then checkBox.HorizontalAlignment = HorizontalAlignment.Right End If Controls.Grid.SetColumn(checkBox, value) grid.Children.Add(checkBox) index += 1 Next End SubEnd Class