StackPanelはコントロールを垂直に縦積みするパネルです。オプションで水平に並べることもできます。
プロジェクトの作成
cd (mkdir NoXAML07)
dotnet new wpf -f net8.0
rm *.xaml
ソースコード
ファイル名:NoXAML07.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<StartupObject>NoXAML07.App</StartupObject>
</PropertyGroup>
</Project>
ファイル名:App.xaml.cs
using System.Windows;
namespace NoXAML07;
public partial class App : Application
{
private static void App_Startup(object sender, StartupEventArgs e)
{
// ウィンドウ本体をコードで生成
var window = new MainWindow
{
Title = "StackPanel",
Width = 400,
Height = 300,
};
window.Show();
}
// エントリポイント
[STAThread]
public static void Main()
{
var app = new App();
// Startup イベントでウィンドウを生成
app.Startup += App_Startup;
app.Run();
}
}
ファイル名:MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;
namespace NoXAML07;
public partial class MainWindow : Window
{
private static UIElement BuildContent()
{
return new Grid
{
Children = {
new StackPanel
{
Children = {
new Label
{
Content = "縦",
Height = 30.0d,
},
new TextBox
{
Text = "縦",
Height = 30.0d,
},
new Button
{
Content = "縦",
Height = 30.0d,
},
new StackPanel
{
Orientation = Orientation.Horizontal,
Height = 100.0d,
Margin = new Thickness(10.0d),
Children = {
new Label
{
Content = "横",
Height = 30.0d,
Width = 100.0d,
},
new TextBox
{
Text = "横",
Height = 30.0d,
Width = 100.0d,
},
new Button
{
Content = "横",
Height = 30.0d,
Width = 100.0d,
},
}
}
}
}
}
};
}
public MainWindow()
{
Content = BuildContent(); // 中身の UI 要素を返すメソッド
}
}
垂直方向に並べる(デフォルト)
Orientation = Orientation.Vertical,
水平方向に並べる
Orientation = Orientation.Horizontal,
四方のマージンを設定
Margin = new Thickness(10.0d),
左右上下のマージンを任意の数値にする。
Margin = new Thickness(10.0d, 20,0d, 30.0d, 40.0d),
順番left,top,right,bottom
実行
dotnet run
コメント