凡庸なUIを脱却せよ:VB.NETによるWPFカスタムコントロールの極限設計
〜TemplateSelectorとControlTemplateによる、堅牢かつ高機能なUIライブラリの構築〜
業務自動化ツールの開発において、多くのエンジニアが陥る罠がある。それは「標準コントロールの組み合わせ(UserControl)」で、無理やり複雑な要件を解決しようとすることだ。
「ボタンを並べて、ラベルを置いて、それっぽく見せる」。
これは「部品の寄せ集め」であって、「コントロールの設計」ではない。
社内のニッチな業務プロセス、例えば「在庫ステータスに応じて表示項目自体が劇的に変化するダッシュボード」や「通信プロトコルの状態によって描画構造が変わる監視パネル」を構築する場合、UserControlによる継承では、コードの肥大化とメンテナンス性の崩壊を招く。
真のプロフェッショナルは、「見た目(Visual)」と「振る舞い(Logic)」を完全に分離した「Custom Control」を設計する。本稿では、VB.NETを用いて、`ControlTemplateSelector`を駆使し、状況に応じて構造そのものを切り替える究極のカスタムコントロールの作り方を伝授する。
1. なぜ UserControl ではなく Custom Control なのか?
まず、設計思想の根本を整理しておこう。ここを履き違えると、プロジェクトの中盤で必ずリファクタリングの泥沼に沈む。
| 特徴 | UserControl (ユーザーコントロール) | Custom Control (カスタムコントロール) |
|---|---|---|
| 設計思想 | 既存の部品を組み合わせて「画面の一部」を作る | 「新しい部品」そのものを定義する |
| 見た目 | XAMLとコードが密結合している | `Generic.xaml` に定義された `ControlTemplate` に依存する |
| 再利用性 | 低い(特定の画面に依存しやすい) | 極めて高い(ライブラリ化が可能) |
| 柔軟性 | 低い(構造の変更が困難) | 高い(TemplateSelectorで構造ごと変えられる) |
業務自動化ツールにおいて、複数のアプリケーションで共通利用できる「社内標準UIライブラリ」を作りたいのであれば、選択肢はCustom Control 一択だ。
2. 実践:ステータス駆動型カスタムコントロールの構築
具体例として、「業務ステータスに応じて、内部構造(レイアウト)が動的に変化する `SmartStatusCard` コントロール」を設計する。
- Normal状態: シンプルなテキスト表示。
- Warning状態: アイコンと詳細メッセージを表示する横長レイアウト。
- Critical状態: 警告アニメーションを伴う、目立つグリッドレイアウト。
これらを、一つのコントロールで、かつ「構造ごと」切り替える実装を見ていこう。
STEP 1: コントロールの核となる DependencyProperty の定義
まず、VB.NETでコントロールの「状態」を保持するプロパティを定義する。ここで重要なのは、DependencyProperty (依存関係プロパティ) を使うことだ。これを使わなければ、WPFの強力なBindingやAnimationの恩恵を一切受けられない。
Imports System.Windows
Imports System.Windows.Controls
''' <summary>
''' 業務ステータスを表す列挙型
''' </summary>
Public Enum BusinessStatus
Normal
Warning
Critical
End Enum
''' <summary>
''' 構造を動的に切り替える高度なカスタムコントロール
''' </summary>
<TemplatePart(Name:="PART_ContentPresenter", Type:=GetType(ContentPresenter))>
Public Class SmartStatusCard
Inherits Control
' 定義: 既定のスタイルキー(Generic.xamlを参照するために必須)
Shared Sub DefaultStyleKey() As Type
Return GetType(SmartStatusCard)
End Sub
' DependencyProperty: ステータス
Public Shared ReadOnly StatusProperty As DependencyProperty =
DependencyProperty.Register(
Name:=NameOf(Status),
Property:=GetType(BusinessStatus),
OwnerType:=GetType(SmartStatusCard),
DefaultValue:=BusinessStatus.Normal,
FrameworkPropertyMetadata=New FrameworkPropertyMetadata(
AddressOf OnStatusChanged,
FrameworkPropertyMetadataOptions.AffectsRender))
Public Property Status As BusinessStatus
Get
Return DirectCast(GetValue(StatusProperty), BusinessStatus)
End Get
Set(value As BusinessStatus)
SetValue(StatusProperty, value)
End Set
End Property
' DependencyProperty: 表示用テキスト
Public Shared ReadOnly DisplayTextProperty As DependencyProperty =
DependencyProperty.Register(
Name:=NameOf(DisplayText),
Property:=GetType(String),
OwnerType:=GetType(SmartStatusCard),
DefaultValue:="")
Public Property DisplayText As String
Get
Return DirectCast(GetValue(DisplayTextProperty), String)
End Get
Set(value As String)
SetValue(DisplayTextProperty, value)
End Set
End Property
' ステータス変更時のコールバック(必要に応じてロジックを挟む)
Private Shared Sub OnStatusChanged(d As Object, e As DependencyPropertyChangedEventArgs)
Dim ctrl = DirectCast(d, SmartStatusCard)
' ここで内部状態に基づいた複雑な計算や、イベントの発火を行うことが可能
End Sub
End Class
STEP 2: ControlTemplateSelector による構造の分岐ロジック
次に、`Status` プロパティの値を見て、「どのテンプレートを使うか」を決定するセレクターを実装する。
Imports System.Windows
''' <summary>
''' ステータスに応じて異なるControlTemplateを返却するセレクター
''' </summary>
Public Class StatusTemplateSelector
Inherits DataTemplateSelector
' XAMLから参照できるように、各テンプレートをプロパティとして定義
Public Property NormalTemplate As DataTemplate
Public Property WarningTemplate As DataTemplate
Public Property CriticalTemplate As DataTemplate
''' <summary>
''' 選択ロジックの実装
''' </summary>
Public Overrides Function SelectTemplate(item As Object, container As DependencyObject) As DataTemplate
' item は SmartStatusCard インスタンスを指す
Dim control = TryCast(item, SmartStatusCard)
If control Is Nothing Then Return Nothing
' ステータスに基づき、適切なテンプレートを返却
Select Case control.Status
Case BusinessStatus.Normal
Return NormalTemplate
Case BusinessStatus.Warning
Return WarningTemplate
Case BusinessStatus.Critical
Return CriticalTemplate
Case Else
Return Nothing
End Select
End Function
End Class
STEP 3: XAML による視覚定義 (Generic.xaml)
ここが腕の見せ所だ。`Themes/Generic.xaml` に、各状態の「見た目」を定義する。プロの設計では、`ControlTemplate` を分けることで、`SmartStatusCard` クラスのコードに一切の描画ロジックを書かない。
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNamespace">
<!-- 1. Normal状態のテンプレート (シンプルな表示) -->
<DataTemplate x:Key="NormalTemplate">
<Border Background="LightGray" CornerRadius="5" Padding="10">
<TextBlock Text="{Binding DisplayText, RelativeSource={RelativeSource TemplatedParent}}"
Foreground="Black" FontWeight="Bold"/>
</Border>
</DataTemplate>
<!-- 2. Warning状態のテンプレート (アイコン付き横長) -->
<DataTemplate x:Key="WarningTemplate">
<Border Background="LightGoldenrodYellow" BorderBrush="Orange" BorderThickness="2" CornerRadius="5" Padding="10">
<StackPanel Orientation="Horizontal">
<Ellipse Width="15" Height="15" Fill="Orange" Margin="0,0,10,0"/>
<TextBlock Text="{Binding DisplayText, RelativeSource={RelativeSource TemplatedParent}}"
Foreground="DarkOrange" VerticalAlignment="Center"/>
</StackPanel>
</Border>
</DataTemplate>
<!-- 3. Critical状態のテンプレート (強調表示) -->
<DataTemplate x:Key="CriticalTemplate">
<Border Background="MistyRose" BorderBrush="Red" BorderThickness="3" CornerRadius="5" Padding="15">
<StackPanel>
<TextBlock Text="!!! ALERT !!!" Foreground="Red" FontWeight="ExtraBold" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding DisplayText, RelativeSource={RelativeSource TemplatedParent}}"
FontSize="18" Foreground="DarkRed" HorizontalAlignment="Center"/>
</StackPanel>
</Border>
</DataTemplate>
<!-- 4. Selector の定義 -->
<local:StatusTemplateSelector x:Key="MyStatusSelector"
NormalTemplate="{StaticResource NormalTemplate}"
WarningTemplate="{StaticResource WarningTemplate}"
CriticalTemplate="{StaticResource CriticalTemplate}"/>
<!-- 5. 本体のスタイル定義 -->
<Style TargetType="{x:Type local:SmartStatusCard}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:SmartStatusCard}">
<!-- ここが肝:Selectorを使って、中身(Content)を切り替える -->
<ContentPresenter Content="{Binding RelativeSource={RelativeSource TemplatedParent}}"
ContentTemplateSelector="{StaticResource MyStatusSelector}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
3. 堅牢な設計のためのアーキテクト・アドバイス
ここまで実装できた君は、すでに凡庸な開発者から一歩抜け出した。しかし、プロダクション環境(本番稼働)に投入する前に、以下の「重み」を理解しておかなければならない。
① データベース・ファイル連携の「隔離」
カスタムコントロールの内部で、直接 `System.Data.SqlClient` や `System.IO` を呼び出すことは絶対に避けてくれ。
コントロールの責務は「データの表示」と「ユーザー操作の通知」のみだ。DBからデータを取ってくるのは `ViewModel`、あるいは `Service` クラスの仕事だ。コントロールが外部リソースに依存した瞬間、ユニットテストは不可能になり、メモリリークの温床となる。
② メモリリークの防波堤
`ControlTemplate` 内で `Event` を購読する場合、コントロールが破棄される際に適切に解除(Unsubscribe)されているかを確認しろ。特に、`Loaded` イベントで外部オブジェクトのイベントに紐付けた場合、`Unloaded` で解除し忘れると、コントロールが画面から消えてもメモリに残り続ける。これは業務ツールが長時間稼働した際の「謎のメモリ増大」の正体だ。
③ パフォーマンスの最適化
`TemplateSelector` は、要素が再描画されるたびに呼び出される可能性がある。セレクター内のロジックは極限までシンプルに保て。複雑な条件分岐や重い計算をセレクターに書くのは、UIスレッドを止める自殺行為だ。
結論
カスタムコントロールを自作する苦労は、最初は高く感じるかもしれない。しかし、一度「堅牢なUIライブラリ」を構築してしまえば、その後の開発スピードは劇的に加速する。
「既存の部品をどう組み合わせるか」ではなく、「業務の概念をどう抽象化し、コントロールとして定義するか」。この視点を持ったとき、君の書くコードは単なるプログラムを超え、真に価値のある「資産」へと昇華する。
さあ、設計図を書き直せ。理想のUIは、君の手の中にある。
