標準の限界を超えろ:WPF CustomControlによる「真の描画制御」と設計思想
業務自動化ツールの開発において、多くのエンジニアが陥る罠がある。それは、「既存のコントロールを組み合わせれば、何でも作れる」という思い込みだ。
製造現場のインジケーター、複雑な時系列チャート、あるいは特殊なステータス表示。これらを実装しようとした際、`Grid`の中に`Ellipse`や`Line`といったShapeオブジェクトを大量に配置して「それっぽく」見せようとする設計は、プロの仕事ではない。それは単なる「オブジェクトの積み重ね」であり、描画負荷(Visual Treeの肥大化)を招き、パフォーマンスを確実に破壊する。
真に高度なUI、すなわち「低負荷で、かつ極めて柔軟なUI」を実現するには、WPFのレンダリングパイプラインの深層に踏み込み、`Control`クラスを継承したCustom Controlを自作する必要がある。
本稿では、VB.NETを用いて`OnRender`メソッドをオーバーライドし、描画命令を直接発行する「極限の描画手法」を伝授する。
1. UserControlとCustomControlの決定的な違い
まず、設計の根幹となる「使い分け」を明確にしておく。ここを間違えると、再利用性の低い、保守不可能なコードが生まれる。
- UserControl (ユーザーコントロール)
- 既存のコントロール(Button, TextBox等)を組み合わせて「一つの部品」としてパッケージングするもの。
- 用途: 特定の画面レイアウトの再利用。
- 欠点: 内部の構造が固定されており、スタイル(Template)の変更が困難。
- Custom Control (カスタムコントロール)
- `Control`クラスを継承し、見た目(Visual)とロジックを完全に分離するもの。
- 用途: 新しい種類のコントロール(独自のチャート、ゲージ、特殊ボタン等)の定義。
- 利点: `Generic.xaml`を用いて「見た目(Template)」を外部から注入できる。Visual TreeにShapeオブジェクトを増やさず、直接描画命令(DrawingContext)を叩けるため、圧倒的に軽量である。
我々が目指すのは、後者である。
2. 実装の核心:`OnRender`による直接描画
WPFにおいて、描画のパフォーマンスを最大化する鍵は、`DrawingContext`にある。Shapeオブジェクト(`Line`や`Rectangle`)は、それ自体が「オブジェクト」としてメモリを消費し、レイアウト計算の対象となる。しかし、`OnRender`内で`DrawingContext`を使用して描画を行う場合、それは単なる「命令のリスト」としてGPUへ送られる。
以下に、製造業のライン監視などで多用される「円形インジケーター(ゲージ)」を例に、堅牢なCustom Controlのコードを示す。
プロダクション・コード例:`CircularGaugeControl`
このコントロールは、単に値を表示するだけでなく、`DependencyProperty`を正しく実装し、値の変化に応じて自動的に再描画(Invalidate)されるよう設計されている。
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
''' <summary>
''' 高性能な円形ゲージコントロール。
''' Shapeオブジェクトを介さず、OnRenderにより直接描画を行う。
''' </summary>
Public Class CircularGaugeControl
Inherits Control
' --- Dependency Properties ---
''' <summary>
''' 現在の値
''' </summary>
Public Shared ReadOnly ValueProperty As DependencyProperty =
DependencyProperty.Register("Value", GetType(Double), GetType(CircularGaugeControl),
New PropertyMetadata(0.0, AddressOf OnValueChanged))
Public Property Value As Double
Get
Return DirectCast(GetValue(ValueProperty), Double)
End Get
Set(value As Double)
SetValue(ValueProperty, value)
End Set
End Property
''' <summary>
''' 最大値
''' </summary>
Public Shared ReadOnly MaxValueProperty As DependencyProperty =
DependencyProperty.Register("MaxValue", GetType(Double), GetType(CircularGaugeControl),
New PropertyMetadata(100.0))
Public Property MaxValue As Double
Get
Return DirectCast(GetValue(MaxValueProperty), Double)
End Get
Set(value As Double)
SetValue(MaxValueProperty, value)
End Set
End Property
''' <summary>
''' ゲージの線の色
''' </summary>
Public Shared ReadOnly GaugeColorProperty As DependencyProperty =
DependencyProperty.Register("GaugeColor", GetType(Brush), GetType(CircularGaugeControl),
New PropertyMetadata(Brushes.DodgerBlue))
Public Property GaugeColor As Brush
Get
Return DirectCast(GetValue(GaugeColorProperty), Brush)
End Get
Set(value As Brush)
SetValue(GaugeColorProperty, value)
End Set
End Property
' --- Constructor ---
Public Sub New()
' Default Styleを適用するために必要(Generic.xamlが定義されている前提)
DefaultStyleKeyProperty.OverrideMetadata(GetType(CircularGaugeControl),
New FrameworkPropertyMetadata(GetType(CircularGaugeControl)))
End Sub
' --- Private Methods ---
''' <summary>
''' プロパティ変更時に再描画を要求する
''' </summary>
Private Shared Sub OnValueChanged(d As Object, e As DependencyPropertyChangedEventArgs)
Dim ctrl As CircularGaugeControl = DirectCast(d, CircularGaugeControl)
' 描画の更新を要求(重要:これを忘れると値が変わっても見た目が変わらない)
ctrl.InvalidateVisual()
End Sub
' --- Rendering Override ---
''' <summary>
''' レンダリングの本体。ここがパフォーマンスの要。
''' </summary>
Protected Overrides Sub OnRender(drawingContext As DrawingContext)
MyBase.OnRender(drawingContext)
' 描画領域の計算
Dim bounds As Rect = New Rect(0, 0, ActualWidth, ActualHeight)
Dim center As New Point(ActualWidth / 2, ActualHeight / 2)
Dim radius As Double = Math.Min(ActualWidth, ActualHeight) / 2 * 0.8
' 1. 背景の円を描画
drawingContext.DrawEllipse(Brushes.Transparent, New Pen(Brushes.LightGray, 10), center, radius, radius)
' 2. 進捗割合の計算
Dim ratio As Double = Math.Min(Value / MaxValue, 1.0)
If ratio < 0 Then ratio = 0
' 3. ゲージ(弧)の描画
' ArcSegmentを使用して、進捗に応じた弧を描く
Dim sweepAngle As Double = ratio * 360.0
' 簡易的な実装として、Penを使用して描画
' ※より高度な描画(太いストロークの端部処理など)を行う場合は、Geometryを使用する
Dim pen As New Pen(GaugeColor, 10)
pen.StartCap = PenLineCap.Round
pen.EndCap = PenLineCap.Round
' 弧の描画ロジック(Geometryの構築)
Dim geometry As Geometry = CreateArcGeometry(center, radius, sweepAngle)
drawingContext.DrawGeometry(Nothing, pen, geometry)
' 4. 中央に数値を描画(テキスト描画)
Dim text As New FormattedText(
$"{Value:F1}",
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
New Typeface("Segoe UI"),
ActualHeight * 0.15,
Brushes.Black,
VisualTreeHelper.GetDpi(Me).PixelsPerDip)
drawingContext.DrawText(text, New Point(center.X - text.Width / 2, center.Y - text.Height / 2))
End Sub
''' <summary>
''' 弧のGeometryを生成するヘルパーメソッド
''' </summary>
Private Function CreateArcGeometry(center As Point, radius As Double, angle As Double) As Geometry
Dim gc As New StreamGeometry()
Using ctx As New StreamGeometryContext()
' 開始点の計算
Dim startAngle As Double = -90 ' 12時の方向から開始
Dim radStart As Double = Math.PI * (startAngle / 180.0)
Dim startPt As New Point(center.X + radius * Math.Cos(radStart), center.Y + radius * Math.Sin(radStart))
ctx.BeginFigure(startPt, False, False)
' 終了点の計算
Dim endAngle As Double = startAngle + angle
Dim radEnd As Double = Math.PI * (endAngle / 180.0)
Dim endPt As New Point(center.X + radius * Math.Cos(radEnd), center.Y + radius * Math.Sin(radEnd))
' 弧を描画(Sizeは半径、SweepDirectionは時計回り)
ctx.ArcTo(endPt, New Size(radius, radius), 0, angle > 180, SweepDirection.Clockwise, True, True)
End Using
gc.Open(gc)
Return gc
End Function
End Class
3. プロフェッショナルが守るべき「堅牢な設計」の鉄則
コードを書くだけでは、プロダクションレベルには達しない。以下の3点は、設計時に必ず脳内に叩き込んでおくことだ。
① データ連携の分離(Decoupling)
コントロールの内部で「データベースから値を取得する」というロジックを書いてはならない。これは致命的な設計ミスだ。コントロールは「渡された値をどう描画するか」だけに集中すべきである。
データの取得・加工はViewModel(MVVMパターン)で行い、コントロールには`DependencyProperty`を通じてバインディングで値を渡す。これが、テスト可能で保守性の高い設計の境界線だ。
② スレッドセーフへの配慮
製造業のデータ収集などで、バックグラウンドスレッドからリアルタイムに値を更新する場合、直接`Value`プロパティを書き換えると`InvalidOperationException`(別スレッドからのUI操作)が発生する。
必ず `Application.Current.Dispatcher.Invoke` を介して更新するか、ViewModel側で適切にDispatcherを制御すること。
③ 無駄な再描画(Invalidation)の抑制
`OnValueChanged` 内で `InvalidateVisual()` を呼び出すのは正しいが、もし値が前回と全く同じ(例えば `10.0` から `10.0` への変更)であれば、呼び出す必要はない。
' 改善例
If Math.Abs(oldValue - newValue) > 0.001 Then
ctrl.InvalidateVisual()
End If
数ミリ秒単位で更新されるインジケーターにおいて、この微細な差がCPU使用率に大きな影響を与える。
4. まとめ:エンジニアとしての視座
`OnRender` を使いこなすということは、WPFというフレームワークの「抽象化された便利さ」に甘んじることなく、その下の「描画エンジン」を直接制御することを意味する。
標準コントロールを組み合わせて「なんとなく」作るエンジニアと、描画のライフサイクルを理解し、`DrawingContext`を操るエンジニア。業務自動化ツールの品質、そしてシステム全体のパフォーマンスを決めるのは、この圧倒的な知識の差である。
君が作るツールが、現場の過酷な環境下でも、滑らかに、かつ正確に動き続けることを願っている。
