WPF(Windows Presentation Foundation)提供多种面板用于布局控件,在前两篇文章中,我们已经介绍了Grid和StackPanel,今天就来介绍另一个常用的面板——WrapPanel。
WrapPanel面板
WrapPanel面板是一种自动换行面板,它会自动将其中的子元素横向排列,在一行排满后会自动换到下一行继续排列,其排列方式类似于流式布局(Flow Layout)。WrapPanel的子元素可以使用不同的宽度和高度,WrapPanel会根据子元素的实际大小进行排列。
WrapPanel的用法非常简单,与其他面板相似,只需要将子元素添加到WrapPanel中即可:
```xml
```
效果如下图所示:

WrapPanel的属性
WrapPanel提供了一些属性来控制其行为和外观,下面介绍其中比较常用的属性:
1. Orientation属性
Orientation属性用于设定容器的排列方向,其值可以是Horizontal表示横向排列,也可以是Vertical表示纵向排列,默认值是Horizontal。
```xml
```
效果如下图所示:

2. ItemHeight和ItemWidth属性
ItemHeight和ItemWidth属性用于设置WrapPanel的每个子元素的高度和宽度,若不设置,则使用子元素实际大小。
```xml
```
效果如下图所示:

3. HorizontalContentAlignment和VerticalContentAlignment属性
WrapPanel可以垂直对齐和水平对齐子元素。使用HorizontalAlignment属性和VerticalAlignment属性设置水平和垂直对齐,可以通过VerticalContentAlignment和HorizontalContentAlignment属性同时设置水平和垂直对齐方式,这两个属性是WrapPanel特有的属性。
```xml
```
效果如下图所示:

案例说明
下面通过一个案例来演示WrapPanel的用法,制作一个类似于Windows桌面快捷方式的效果,当窗口大小变化时,WrapPanel会自动换行以适应窗口大小。
首先,创建一个WPF应用程序,在MainWindow.xaml中添加如下代码:
```xml
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WrapPanel Demo" Height="350" Width="525"> HorizontalAlignment="Center" VerticalAlignment="Top" Orientation="Horizontal" ItemWidth="100" ItemHeight="100" Height="Auto" Width="Auto" Margin="5"/>
```
接下来,我们需要通过C#代码来生成快捷方式图标,这里通过遍历指定文件夹中的文件,生成图标,并将其添加到WrapPanel中。代码如下:
```csharp
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo folder = new DirectoryInfo(folderPath);
foreach (FileInfo file in folder.GetFiles())
{
if (file.Extension == ".lnk")
{
Image image = new Image();
image.Width = 64;
image.Height = 64;
image.Margin = new Thickness(5);
image.HorizontalAlignment = HorizontalAlignment.Center;
image.VerticalAlignment = VerticalAlignment.Center;
image.Stretch = Stretch.Uniform;
BitmapSource bitmap = ToBitmapSource(GetShortcutIcon(file.FullName));
image.Source = bitmap;
wrapPanel.Children.Add(image);
}
}
}
// 将Icon转换为BitmapSource类型
private static BitmapSource ToBitmapSource(System.Drawing.Icon icon)
{
BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
return bitmapSource;
}
// 获取快捷方式的图标
private static System.Drawing.Icon GetShortcutIcon(string filePath)
{
System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
return icon;
}
}
```
完整的程序运行效果如下图所示:

总结
WrapPanel是一种自动换行面板,非常适用于需要根据窗口尺寸自适应排列子元素的场景。它可以通过设置属性来控制排列方向、子元素的高度和宽度、对齐方式等。同时,WrapPanel也可以与其他面板结合使用,例如将WrapPanel作为StackPanel或Grid中的一个子元素使用。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.ynyuzhu.com/
你说我是猪,跟我交往根绝没有意思,那么我问你,既然你都能跟猪交往,可见你的境界很高。