WPFで不規則な形状のウィンドウを実現の方法
WPF で不規則なウィンドウを実現するには、次の手順に従います。
- 新しい WPF プロジェクトを作成します。
- 「CustomWindow.xaml」といった名前で、プロジェクトに新しいフォームを追加する。
- CustomWindow.xaml ファイルでは、グリッド レイアウトを使用して、フォームのコンテンツを定義します。
- ウィンドウのスタイルで、ウィンドウの枠を「なし」に設定し、標準的な長方形の枠をなくします。
- CustomWindow.xaml.cs(フォームのコードファイル)に次のコードを追加して、フォームのドラッグアンドサイズ変更動作を処理します。
public partial class CustomWindow : Window
{
public CustomWindow()
{
InitializeComponent();
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DragMove();
}
private void Window_Resize(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (WindowState == WindowState.Maximized)
{
WindowState = WindowState.Normal;
}
else
{
WindowState = WindowState.Maximized;
}
}
}
}
- CustomWindow.xaml ファイルで、ウィンドウの Style プロパティーをカスタムスタイルに設定し、ウィンドウのイベントを上記コード内のイベントハンドラーにバインドします。
<Window x:Class="WpfApp1.CustomWindow"
...
Style="{StaticResource CustomWindowStyle}"
MouseLeftButtonDown="Window_MouseLeftButtonDown"
MouseLeftButtonUp="Window_Resize">
<Grid>
<!-- 窗体内容 -->
</Grid>
</Window>
- App.xamlファイルでCustomWindowStyleというカスタムウィンドウスタイルを定義する
<Application.Resources>
<Style TargetType="Window" x:Key="CustomWindowStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border Background="Transparent">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" Background="Gray" Height="30">
<!-- 窗体标题栏 -->
</Border>
<ContentPresenter Grid.Row="1"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="WindowStyle" Value="None"/>
<Setter Property="AllowsTransparency" Value="True"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip"/>
</Style>
</Application.Resources>
- App.xaml.cs ファイルで既定フォームをカスタムフォームとして設定します:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow mainWindow = new CustomWindow();
mainWindow.Show();
}
}
独自のフォームスタイルとレイアウトを作成することによって、不規則なフォームを実現します。