在C#中,可以使用Windows Forms或WPF來實現固定布局的響應式設計。這里分別為兩者提供一個簡單的示例。
首先,需要安裝ResponsiveWindowsForms項目(https://github.com/MahApps/ResponsiveWindowsForms)。通過NuGet包管理器安裝ResponsiveWindowsForms庫。
然后,創建一個新的Windows Forms項目,并在Form1上添加控件。
using System;
using System.Drawing;
using System.Windows.Forms;
using ResponsiveWindowsForms;
namespace WindowsFormsResponsiveLayout
{
public partial class Form1 : Form
{
private readonly ResponsiveForm responsiveForm;
public Form1()
{
InitializeComponent();
// 初始化ResponsiveForm
responsiveForm = new ResponsiveForm(this);
// 添加響應式布局
responsiveForm.AddRange(new[]
{
new ResponsiveRow(new[]
{
new ResponsiveControl(label1, new RectangleF(0, 0, 50, 100), ResponsiveAlignment.Center),
new ResponsiveControl(textBox1, new RectangleF(50, 0, 50, 100), ResponsiveAlignment.Center)
}),
new ResponsiveRow(new[]
{
new ResponsiveControl(button1, new RectangleF(0, 0, 100, 100), ResponsiveAlignment.Center)
})
});
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
// 更新響應式布局
responsiveForm.UpdateLayout();
}
}
}
在WPF中,可以使用Grid和ColumnDefinition來實現響應式布局。創建一個新的WPF項目,并在MainWindow上添加控件。
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfResponsiveLayout"
mc:Ignorable="d"
Title="MainWindow" Height="150" Width="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Column="0" Grid.Row="0" Content="Label:" VerticalAlignment="Center"/>
<TextBox Grid.Column="1" Grid.Row="0" VerticalAlignment="Center"/>
<Button Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2" Content="Button" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>
這樣,在調整窗口大小時,布局會自動適應屏幕尺寸。