Margin・Padding・Background
WPF のレイアウトや見た目を整えるときに基本になるのが以下の3つです。
プロパティ | 説明 |
---|---|
Margin | コントロールの外側の余白(親コンテナとの間隔) |
Padding | コントロール内側の余白(境界線から内容までの間隔) |
Background | 背景色(Brush で指定) |
ファイル名:NoXAML33.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
ファイル名:App.cs
using System;
using System.Windows;
namespace NoXAML33;
public class App : Application
{
[STAThread]
public static void Main(string[] args)
{
var app = new App();
app.Run();
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var win = new MainWindow();
win.Show();
}
}
ファイル名:AssemblyInfo.cs
using System.Windows;
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
ファイル名:MainWindow.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace NoXAML33;
public class MainWindow : Window
{
public MainWindow()
{
this.Title = "コントロールの余白と背景色";
this.Width = 400;
this.Height = 300;
// StackPanelを配置
var panel = new StackPanel
{
Margin = new Thickness(10), // ウィンドウ内側の余白
Background = Brushes.White
};
// ボタン作成(外側余白 + 内側余白 + 背景色)
var button = new Button
{
Content = "クリックしてください",
Margin = new Thickness(20), // 親(panel)との間隔
Padding = new Thickness(15, 5, 15, 5), // 内側余白(文字との間隔)
Background = Brushes.LightBlue
};
// テキストボックス作成(背景色 + Padding)
var textBox = new TextBox
{
Text = "背景色と余白の例",
Margin = new Thickness(20, 0, 20, 10),
Padding = new Thickness(10),
Background = Brushes.LightYellow
};
panel.Children.Add(button);
panel.Children.Add(textBox);
this.Content = panel;
}
}
コメント