更新 : 2007 年 11 月
このチュートリアルでは、Windows Presentation Foundation (WPF) カスタム コントロール用のデザイン時装飾をデバッグする方法について説明します。装飾は、単純な自動サイズ機能を提供するチェック ボックスです。
このチュートリアルでは次のタスクを行います。
WPF カスタム コントロール ライブラリ プロジェクトを作成する。
デザイン時メタデータに対する個別のアセンブリを作成する。
装飾プロバイダを実装する。
デザイン時にコントロールをテストする。
デザイン時デバッグのためのプロジェクトを設定する。
デザイン時にコントロールをデバッグする。
このチュートリアルを終了すると、カスタム コントロール用装飾をデバッグする方法を習得できます。
![]() |
---|
使用している設定またはエディションによっては、表示されるダイアログ ボックスやメニュー コマンドがヘルプに記載されている内容と異なる場合があります。設定を変更するには、[ツール] メニューの [設定のインポートとエクスポート] をクリックします。詳細については、「Visual Studio の設定」を参照してください。 |
前提条件
このチュートリアルを完了するには、次のコンポーネントが必要です。
- Visual Studio 2008.
カスタム コントロールの作成
最初に、カスタム コントロールのプロジェクトを作成します。コントロールは、デザイン時コードが少量のボタンにします。このボタンは、GetIsInDesignMode メソッドを使用して、デザイン時動作を実装します。
カスタム コントロールを作成するには
Visual Basic または Visual C# で AutoSizeButtonLibrary という名前の新しい WPF カスタム コントロール ライブラリ プロジェクトを作成します。
コード エディタで CustomControl1 のコードが開きます。
ソリューション エクスプローラで、コード ファイル名を AutoSizeButton.cs または AutoSizeButton.vb に変更します。このプロジェクト内のすべての参照について名前を変更するかどうかをたずねるメッセージ ボックスが開いたら、[はい] をクリックします。
ソリューション エクスプローラで、Themes フォルダを展開します。
Generic.xaml をダブルクリックします。
WPF デザイナで Generic.xaml が開きます。
XAML ビューで、"CustomControl1" の出現箇所をすべて "AutoSizeButton" に置き換えます。
コード エディタで AutoSizeButton.cs または AutoSizeButton.vb を開きます。
自動的に生成されたコードを次のコードに置き換えます。このコードは、Button からの継承で、ボタンがデザイナに表示されると、"Design mode active" というテキストを表示します。
Imports System Imports System.Collections.Generic Imports System.Text Imports System.Windows.Controls Imports System.Windows.Media Imports System.ComponentModel ' The AutoSizeButton control implements a button ' with a custom design-time experience. Public Class AutoSizeButton Inherits Button Public Sub New() ' The following code enables custom design-mode logic. ' The GetIsInDesignMode check and the following design-time ' code are optional and shown only for demonstration. If DesignerProperties.GetIsInDesignMode(Me) Then Content = "Design mode active" End If End Sub End Class
using System; using System.Collections.Generic; using System.Text; using System.Windows.Controls; using System.Windows.Media; using System.ComponentModel; namespace AutoSizeButtonLibrary { // The AutoSizeButton control implements a button // with a custom design-time experience. public class AutoSizeButton : Button { public AutoSizeButton() { // The following code enables custom design-mode logic. // The GetIsInDesignMode check and the following design-time // code are optional and shown only for demonstration. if (DesignerProperties.GetIsInDesignMode(this)) { Content = "Design mode active"; } } } }
プロジェクトの出力パスを "bin\" に設定します。
ソリューションをビルドします。
デザイン時メタデータ アセンブリの作成
デザイン時コードは、特殊なメタデータ アセンブリに配置されます。このチュートリアルでは、カスタム装飾は、AutoSizeButtonLibrary.VisualStudio.Design という名前のアセンブリに配置されます。詳細については、「メタデータ ストア」を参照してください。
デザイン時メタデータ アセンブリを作成するには
Visual Basic または Visual C# の AutoSizeButtonLibrary.VisualStudio.Design という名前の新しいクラス ライブラリ プロジェクトをソリューションに追加します。
プロジェクトの出力パスを "..\AutoSizeButtonLibrary\bin\" に設定します。これにより、コントロールのアセンブリとメタデータのアセンブリが同じフォルダ内に配置されるため、デザイナがメタデータを検出できます。
次の WPF アセンブリへの参照を追加します。
PresentationCore
PresentationFramework
WindowsBase
次の WPF デザイナ アセンブリへの参照を追加します。
Microsoft.Windows.Design
Microsoft.Windows.Design.Extensibility
Microsoft.Windows.Design.Interaction
AutoSizeButtonLibrary プロジェクトへの参照を追加します。
ソリューション エクスプローラで、Class1 コード ファイル名を Metadata.cs または Metadata.vb に変更します。このプロジェクト内のすべての参照について名前を変更するかどうかをたずねるメッセージ ボックスが開いたら、[はい] をクリックします。
自動的に生成されたコードを次のコードに置き換えます。このコードにより、カスタム デザイン時実装を AutoSizeButton クラスに関連付ける AttributeTable が作成されます。
Imports System Imports System.Collections.Generic Imports System.Text Imports System.ComponentModel Imports System.Windows.Media Imports System.Windows.Controls Imports System.Windows Imports AutoSizeButtonLibrary Imports Microsoft.Windows.Design.Features Imports Microsoft.Windows.Design.Metadata Imports AutoSizeButtonLibrary.VisualStudio.Design ' Container for any general design-time metadata to initialize. ' Designers look for a type in the design-time assembly that ' implements IRegisterMetadata. If found, designers instantiate ' this class and call its Register() method automatically. Friend Class Metadata Implements IRegisterMetadata ' Called by the designer to register any design-time metadata. Public Sub Register() Implements IRegisterMetadata.Register Dim builder As New AttributeTableBuilder() builder.AddCustomAttributes(GetType(AutoSizeButton), New FeatureAttribute(GetType(AutoSizeAdornerProvider))) MetadataStore.AddAttributeTable(builder.CreateTable()) End Sub End Class
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Windows.Media; using System.Windows.Controls; using System.Windows; using AutoSizeButtonLibrary; using Microsoft.Windows.Design.Features; using Microsoft.Windows.Design.Metadata; using AutoSizeButtonLibrary.VisualStudio.Design; namespace AutoSizeButtonLibrary.VisualStudio.Design { // Container for any general design-time metadata to initialize. // Designers look for a type in the design-time assembly that // implements IRegisterMetadata. If found, designers instantiate // this class and call its Register() method automatically. internal class Metadata : IRegisterMetadata { // Called by the designer to register any design-time metadata. public void Register() { AttributeTableBuilder builder = new AttributeTableBuilder(); builder.AddCustomAttributes( typeof(AutoSizeButton), new FeatureAttribute(typeof(AutoSizeAdornerProvider))); MetadataStore.AddAttributeTable(builder.CreateTable()); } } }
ソリューションを保存します。
装飾プロバイダの実装
装飾プロバイダは AutoSizeAdornerProvider という名前の型で実装されます。この装飾 FeatureProvider により、コントロールの Height プロパティおよび Width プロパティをデザイン時に設定できるようになります。
装飾プロバイダを実装するには
AutoSizeAdornerProvider という名前の新しいクラスを AutoSizeButtonLibrary.VisualStudio.Design プロジェクトに追加します。
AutoSizeAdornerProvider のコード エディタで、自動的に生成されたコードを次のコードに置き換えます。このコードにより、CheckBox コントロールに基づく装飾を提供する PrimarySelectionAdornerProvider を実装します。
Imports System Imports System.Collections.Generic Imports System.Text Imports System.Windows.Input Imports System.Windows Imports System.Windows.Automation Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Shapes Imports Microsoft.Windows.Design.Interaction Imports Microsoft.Windows.Design.Model ' The following class implements an adorner provider for the ' AutoSizeButton control. The adorner is a CheckBox control, which ' changes the Height and Width of the AutoSizeButton to "Auto", ' which is represented by double.NaN. Public Class AutoSizeAdornerProvider Inherits PrimarySelectionAdornerProvider Private settingProperties As Boolean Private adornedControlModel As ModelItem Private autoSizeCheckBox As CheckBox Private autoSizeAdornerPanel As AdornerPanel ' The constructor sets up the adorner control. Public Sub New() autoSizeCheckBox = New CheckBox() autoSizeCheckBox.Content = "AutoSize" autoSizeCheckBox.IsChecked = True autoSizeCheckBox.FontFamily = AdornerFonts.FontFamily autoSizeCheckBox.FontSize = AdornerFonts.FontSize autoSizeCheckBox.Background = CType( _ AdornerResources.FindResource(AdornerColors.RailFillBrushKey), _ Brush) End Sub ' The following method is called when the adorner is activated. ' It creates the adorner control, sets up the adorner panel, ' and attaches a ModelItem to the AutoSizeButton. Protected Overrides Sub Activate(ByVal item As ModelItem, ByVal view As DependencyObject) ' Save the ModelItem and hook into when it changes. ' This enables updating the slider position when ' a new background value is set. adornedControlModel = item AddHandler adornedControlModel.PropertyChanged, AddressOf AdornedControlModel_PropertyChanged ' All adorners are placed in an AdornerPanel ' for sizing and layout support. Dim panel As AdornerPanel = Me.Panel ' Set up the adorner's placement. Dim placement As New AdornerPlacementCollection() AdornerPanel.SetHorizontalStretch(autoSizeCheckBox, AdornerStretch.None) AdornerPanel.SetVerticalStretch(autoSizeCheckBox, AdornerStretch.None) panel.CoordinateSpace = AdornerCoordinateSpaces.Layout placement.SizeRelativeToAdornerDesiredWidth(1.0, 0) placement.SizeRelativeToAdornerDesiredHeight(1.0, 0) placement.PositionRelativeToAdornerHeight(-1.0, -23) placement.PositionRelativeToAdornerWidth(0, -23) AdornerPanel.SetPlacements(autoSizeCheckBox, placement) ' Listen for changes to the checked state. AddHandler autoSizeCheckBox.Checked, AddressOf autoSizeCheckBox_Checked AddHandler autoSizeCheckBox.Unchecked, AddressOf autoSizeCheckBox_Unchecked ' Run the base implementation. MyBase.Activate(item, view) End Sub ' The Panel utility property demand-creates the ' adorner panel and adds it to the provider's ' Adorners collection. Public ReadOnly Property Panel() As AdornerPanel Get If Me.autoSizeAdornerPanel Is Nothing Then Me.autoSizeAdornerPanel = New AdornerPanel() ' Add the adorner to the adorner panel. Me.autoSizeAdornerPanel.Children.Add(autoSizeCheckBox) ' Add the panel to the Adorners collection. Adorners.Add(autoSizeAdornerPanel) End If Return Me.autoSizeAdornerPanel End Get End Property ' The following code handles the Checked event. ' It autosizes the adorned control's Height and Width. Sub autoSizeCheckBox_Checked(ByVal sender As Object, ByVal e As RoutedEventArgs) Me.SetHeightAndWidth(True) End Sub ' The following code handles the Unchecked event. ' It sets the adorned control's Height and Width to a hard-coded value. Sub autoSizeCheckBox_Unchecked(ByVal sender As Object, ByVal e As RoutedEventArgs) Me.SetHeightAndWidth(False) End Sub ' The SetHeightAndWidth utility method sets the Height and Width ' properties through the model and commits the change. Private Sub SetHeightAndWidth(ByVal [auto] As Boolean) settingProperties = True Dim batchedChange As ModelEditingScope = adornedControlModel.BeginEdit() Try Dim widthProperty As ModelProperty = adornedControlModel.Properties(Control.WidthProperty) Dim heightProperty As ModelProperty = adornedControlModel.Properties(Control.HeightProperty) If [auto] Then widthProperty.ClearValue() heightProperty.ClearValue() Else widthProperty.SetValue(20.0) heightProperty.SetValue(20.0) End If batchedChange.Complete() Finally batchedChange.Dispose() settingProperties = False End Try End Sub ' The following method deactivates the adorner. Protected Overrides Sub Deactivate() RemoveHandler adornedControlModel.PropertyChanged, _ AddressOf AdornedControlModel_PropertyChanged MyBase.Deactivate() End Sub ' The following method handles the PropertyChanged event. Sub AdornedControlModel_PropertyChanged( _ ByVal sender As Object, _ ByVal e As System.ComponentModel.PropertyChangedEventArgs) If settingProperties Then Return If e.PropertyName = "Height" Or e.PropertyName = "Width" Then Dim h As Double = CType(adornedControlModel.Properties(Control.HeightProperty).ComputedValue, Double) Dim w As Double = CType(adornedControlModel.Properties(Control.WidthProperty).ComputedValue, Double) If Double.IsNaN(h) And Double.IsNaN(w) Then autoSizeCheckBox.IsChecked = True Else autoSizeCheckBox.IsChecked = False End If End If End Sub End Class
using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using Microsoft.Windows.Design.Interaction; using Microsoft.Windows.Design.Model; namespace AutoSizeButtonLibrary.VisualStudio.Design { // The following class implements an adorner provider for the // AutoSizeButton control. The adorner is a CheckBox control, which // changes the Height and Width of the AutoSizeButton to "Auto", // which is represented by double.NaN. public class AutoSizeAdornerProvider : PrimarySelectionAdornerProvider { bool settingProperties; private ModelItem adornedControlModel; CheckBox autoSizeCheckBox; AdornerPanel autoSizeAdornerPanel; // The constructor sets up the adorner control. public AutoSizeAdornerProvider() { autoSizeCheckBox = new CheckBox(); autoSizeCheckBox.Content = "AutoSize"; autoSizeCheckBox.IsChecked = true; autoSizeCheckBox.FontFamily = AdornerFonts.FontFamily; autoSizeCheckBox.FontSize = AdornerFonts.FontSize; autoSizeCheckBox.Background = AdornerResources.FindResource( AdornerColors.RailFillBrushKey) as Brush; } // The following method is called when the adorner is activated. // It creates the adorner control, sets up the adorner panel, // and attaches a ModelItem to the AutoSizeButton. protected override void Activate(ModelItem item, DependencyObject view) { // Save the ModelItem and hook into when it changes. // This enables updating the slider position when // a new background value is set. adornedControlModel = item; adornedControlModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler( AdornedControlModel_PropertyChanged); // All adorners are placed in an AdornerPanel // for sizing and layout support. AdornerPanel panel = this.Panel; // Set up the adorner's placement. AdornerPlacementCollection placement = new AdornerPlacementCollection(); AdornerPanel.SetHorizontalStretch(autoSizeCheckBox, AdornerStretch.None); AdornerPanel.SetVerticalStretch(autoSizeCheckBox, AdornerStretch.None); panel.CoordinateSpace = AdornerCoordinateSpaces.Layout; placement.SizeRelativeToAdornerDesiredWidth(1.0, 0); placement.SizeRelativeToAdornerDesiredHeight(1.0, 0); placement.PositionRelativeToAdornerHeight(-1.0, -23); placement.PositionRelativeToAdornerWidth(0, -23); AdornerPanel.SetPlacements(autoSizeCheckBox, placement); // Listen for changes to the checked state. autoSizeCheckBox.Checked += new RoutedEventHandler(autoSizeCheckBox_Checked); autoSizeCheckBox.Unchecked += new RoutedEventHandler(autoSizeCheckBox_Unchecked); // Run the base implementation. base.Activate(item, view); } // The Panel utility property demand-creates the // adorner panel and adds it to the provider's // Adorners collection. private AdornerPanel Panel { get { if (this.autoSizeAdornerPanel == null) { autoSizeAdornerPanel = new AdornerPanel(); // Add the adorner to the adorner panel. autoSizeAdornerPanel.Children.Add(autoSizeCheckBox); // Add the panel to the Adorners collection. Adorners.Add(autoSizeAdornerPanel); } return this.autoSizeAdornerPanel; } } // The following code handles the Checked event. // It autosizes the adorned control's Height and Width. void autoSizeCheckBox_Checked(object sender, RoutedEventArgs e) { this.SetHeightAndWidth(true); } // The following code handles the Unchecked event. // It sets the adorned control's Height and Width to a hard-coded value. void autoSizeCheckBox_Unchecked(object sender, RoutedEventArgs e) { this.SetHeightAndWidth(false); } // The SetHeightAndWidth utility method sets the Height and Width // properties through the model and commits the change. private void SetHeightAndWidth(bool autoSize) { settingProperties = true; try { using (ModelEditingScope batchedChange = adornedControlModel.BeginEdit()) { ModelProperty widthProperty = adornedControlModel.Properties[Control.WidthProperty]; ModelProperty heightProperty = adornedControlModel.Properties[Control.HeightProperty]; if (autoSize) { widthProperty.ClearValue(); heightProperty.ClearValue(); } else { widthProperty.SetValue(20d); heightProperty.SetValue(20d); } batchedChange.Complete(); } } finally { settingProperties = false; } } // The following method deactivates the adorner. protected override void Deactivate() { adornedControlModel.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler( AdornedControlModel_PropertyChanged); base.Deactivate(); } // The following method handles the PropertyChanged event. void AdornedControlModel_PropertyChanged( object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (settingProperties) { return; } if (e.PropertyName == "Height" || e.PropertyName == "Width") { double h = (double)adornedControlModel.Properties[Control.HeightProperty].ComputedValue; double w = (double)adornedControlModel.Properties[Control.WidthProperty].ComputedValue; autoSizeCheckBox.IsChecked = (h == double.NaN && w == double.NaN) ? true : false; } } } }
ソリューションをビルドします。
デザイン時実装のテスト
AutoSizeButton コントロールは、他の WPF コントロールと同じように使用できます。WPF デザイナは、すべてのデザイン時オブジェクトの作成を処理します。
デザイン時実装をテストするには
DemoApplication という名前の新しい WPF アプリケーション プロジェクトをソリューションに追加します。
WPF デザイナで Window1.xaml が開きます。
AutoSizeButtonLibrary プロジェクトへの参照を追加します。
XAML ビューで、自動的に生成されたコードを次のコードに置き換えます。この XAML により、AutoSizeButtonLibrary 名前空間への参照が追加され、AutoSizeButton カスタム コントロールが追加されます。ボタンは、"Design mode active" というテキストと共にデザイン ビューに表示されます。これは、現在デザイン モードであることを示すものです。ボタンが表示されない場合は、デザイナの一番上の情報バーをクリックして、ビューの再読み込みを行う必要があります。
<Window x:Class="DemoApplication.Window1" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:ab="clr-namespace:AutoSizeButtonLibrary;assembly=AutoSizeButtonLibrary" Title="Window1" Height="300" Width="300"> <Grid> <ab:AutoSizeButton /> </Grid> </Window>
<Window x:Class="DemoApplication.Window1" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:ab="clr-namespace:AutoSizeButtonLibrary;assembly=AutoSizeButtonLibrary" Title="Window1" Height="300" Width="300"> <Grid> <ab:AutoSizeButton Height="Auto" Width="Auto" /> </Grid> </Window>
デザイン ビューで、AutoSizeButton コントロールをクリックして選択します。
CheckBox コントロールが AutoSizeButton コントロールの上に表示されます。
チェック ボックス装飾をオフにします。
コントロールのサイズが小さくなります。チェック ボックス装飾は、装飾されるコントロールを基準とする相対的な位置を保持するように移動します。
デザイン時デバッグのためのプロジェクト設定
この時点で、デザイン時実装は完了しています。次に、Visual Studio を使用してブレークポイントを設定し、デザイン時コードにステップ インします。デザイン時実装をデバッグするには、Visual Studio の別のインスタンスを、現在の Visual Studio セッションにアタッチします。
デザイン時デバッグのためにプロジェクトを設定するには
ソリューション エクスプローラで、DemoApplication プロジェクトを右クリックし、[スタートアップ プロジェクトに設定] をクリックします。
ソリューション エクスプローラで、DemoApplication プロジェクト名を右クリックし、[プロパティ] をクリックします。
DemoApplication プロジェクト デザイナが表示されたら、[デバッグ] タブをクリックします。
[開始動作] セクションで、[外部プログラムの開始] を選択します。Visual Studio の個別のインスタンスがデバッグされます。
省略記号ボタン (
) をクリックして [ファイルの選択] ダイアログ ボックスを開きます。
Visual Studio を参照します。実行可能ファイルの名前は devenv.exe です。Visual Studio を既定の場所にインストールした場合、ファイルのパスは "%programfiles%\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" になります。
[開く] をクリックして devenv.exe を選択します。
カスタム コントロールのデザイン時のデバッグ
これで、カスタム コントロールをデザイン モードで実行しながらデバッグする準備ができました。デバッグ セッションを開始すると、Visual Studio の新しいインスタンスが作成されます。そのインスタンスを使用して、AutoSizeButtonLibrary ソリューションを読み込みます。WPF デザイナで Window1.xaml を開くと、カスタム コントロールのインスタンスが作成され、実行を開始します。
カスタム コントロールをデザイン時にデバッグするには
コード エディタで AutoSizeButton コード ファイルを開き、コンストラクタにブレークポイントを追加します。
コード エディタで Metadata.cs または Metadata.vb を開き、Register メソッドにブレークポイントを追加します。
コード エディタで AutoSizeAdornerProvider.cs または AutoSizeAdornerProvider.vb を開き、コンストラクタにブレークポイントを追加します。
AutoSizeAdornerProvider クラスの残りのメソッドにブレークポイントを追加します。
F5 キーを押してデバッグ セッションを開始します。
Visual Studio の 2 番目のインスタンスが作成されます。デバッグ インスタンスと 2 番目のインスタンスは、次の 2 つの方法で識別できます。
デバッグ インスタンスのタイトル バーに "実行中" と表示されます。
デバッグ インスタンスの [デバッグ] ツール バーの [開始] ボタンが無効になります。
デバッグ インスタンスにブレークポイントが設定されます。
Visual Studio の 2 番目のインスタンスで、AutoSizeButtonLibrary ソリューションを開きます。
WPF デザイナで Window1.xaml を開きます。
Visual Studio のデバッグ インスタンスがフォーカスを取得し、Register 内のブレークポイントで実行が停止します。
F5 キーを押してデバッグを続けます。
AutoSizeButton コンストラクタ内のブレークポイントで実行が中断されます。
F5 キーを押してデバッグを続けます。
Visual Studio の 2 番目のインスタンスがフォーカスを取得し、WPF デザイナが表示されます。
デザイン ビューで、AutoSizeButton コントロールをクリックして選択します。
Visual Studio のデバッグ インスタンスがフォーカスを取得し、AutoSizeAdornerProvider コンストラクタ内のブレークポイントで実行が停止します。
F5 キーを押してデバッグを続けます。
Activate メソッド内のブレークポイントで実行が中断されます。
F5 キーを押してデバッグを続けます。
Visual Studio の 2 番目のインスタンスがフォーカスを取得し、WPF デザイナが表示されます。チェック ボックス装飾が、AutoSizeButton の上と左に表示されます。
操作が終了したら、Visual Studio の 2 番目のインスタンスを閉じるか、デバッグ インスタンスの [デバッグの停止] をクリックして、デバッグ セッションを終了できます。
次の手順
カスタム コントロールに、さらにカスタム デザイン時機能を追加できます。
コントロールのデザイン時にカスタム装飾を追加します。詳細については、「チュートリアル : デザイン時装飾の作成」を参照してください。
[プロパティ] ウィンドウで使用できるカスタム型用のエディタを作成します。詳細については、「方法 : 値エディタを作成する」を参照してください。
[プロパティ] ウィンドウで使用できるカラー エディタを作成します。詳細については、「チュートリアル : カラー エディタの実装」を参照してください。
参照
参照
PrimarySelectionAdornerProvider