参考链接

《WPF编程宝典》3.3.1
《深入浅出WPF》5.4.6

实践

官方实践

  1. <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowTitle="WrapPanel Sample">
  2. <Border HorizontalAlignment="Left" VerticalAlignment="Top" BorderBrush="Black" BorderThickness="2">
  3. <WrapPanel Background="LightBlue" Width="200" Height="100">
  4. <Button Width="200">Button 1</Button>
  5. <Button>Button 2</Button>
  6. <Button>Button 3</Button>
  7. <Button>Button 4</Button>
  8. </WrapPanel>
  9. </Border>
  10. </Page>
  1. // Create the application's main window
  2. mainWindow = new System.Windows.Window();
  3. mainWindow.Title = "WrapPanel Sample";
  4. // Instantiate a new WrapPanel and set properties
  5. myWrapPanel = new WrapPanel();
  6. myWrapPanel.Background = System.Windows.Media.Brushes.Azure;
  7. myWrapPanel.Orientation = Orientation.Horizontal;
  8. myWrapPanel.Width = 200;
  9. myWrapPanel.HorizontalAlignment = HorizontalAlignment.Left;
  10. myWrapPanel.VerticalAlignment = VerticalAlignment.Top;
  11. // Define 3 button elements. The last three buttons are sized at width
  12. // of 75, so the forth button wraps to the next line.
  13. btn1 = new Button();
  14. btn1.Content = "Button 1";
  15. btn1.Width = 200;
  16. btn2 = new Button();
  17. btn2.Content = "Button 2";
  18. btn2.Width = 75;
  19. btn3 = new Button();
  20. btn3.Content = "Button 3";
  21. btn3.Width = 75;
  22. btn4 = new Button();
  23. btn4.Content = "Button 4";
  24. btn4.Width = 75;
  25. // Add the buttons to the parent WrapPanel using the Children.Add method.
  26. myWrapPanel.Children.Add(btn1);
  27. myWrapPanel.Children.Add(btn2);
  28. myWrapPanel.Children.Add(btn3);
  29. myWrapPanel.Children.Add(btn4);
  30. // Add the WrapPanel to the MainWindow as Content
  31. mainWindow.Content = myWrapPanel;
  32. mainWindow.Show();

已编译的应用程序将生成如下所示的新 UI。
WrapPanel - 图1