次の方法で共有


チュートリアル : コントロール内でのレールの実装

このチュートリアルでは、Windows Presentation Foundation (WPF) カスタム コントロール用のレール装飾を作成する方法について説明します。 レール装飾は、コントロールの 1 つの辺にマーカーまたは規則を追加します。単一の軸に沿ったスケーリングは行われません。 装飾は、コントロール内に配置されるスライダーです。 この装飾を使用して、カスタム ボタン コントロールの RenderTransform プロパティを設定できます。 RenderTransform プロパティを設定すると、コントロールが傾斜します。 完全なコード一覧については、WPF Designer Extensibility Samples (WPF デザイナー機能拡張のサンプル) サイトに掲載されている「Skew Adorner (傾斜装飾)」のサンプルを参照してください。 .

このチュートリアルでは次のタスクを行います。

  • WPF カスタム コントロール ライブラリ プロジェクトを作成する。

  • デザイン時メタデータに対する個別のアセンブリを作成する。

  • 装飾プロバイダーを実装する。

  • デザイン時にコントロールをテストする。

このチュートリアルを終了すると、カスタム コントロール用の装飾を作成する方法を習得できます。

注意

実際に画面に表示されるダイアログ ボックスとメニュー コマンドは、アクティブな設定またはエディションによっては、ヘルプの説明と異なる場合があります。 設定を変更するには、[ツール] メニューの [設定のインポートとエクスポート] をクリックします。 詳細については、「設定の操作」を参照してください。

必須コンポーネント

このチュートリアルを実行するには、次のコンポーネントが必要です。

  • Visual Studio 2010.

カスタム コントロールの作成

最初に、カスタム コントロールのプロジェクトを作成します。 コントロールは、デザイン時コードが少量のシンプルなボタンにします。このボタンは、GetIsInDesignMode メソッドを使用して、デザイン時動作を実装します。

カスタム コントロールを作成するには

  1. Visual Basic または Visual C# で SkewButtonLibrary という名前の新しい WPF カスタム コントロール ライブラリ プロジェクトを作成します。

    コード エディターで CustomControl1 のコードが開きます。

  2. ソリューション エクスプローラーで、コード ファイル名を SkewButton.cs または SkewButton.vb に変更します。 このプロジェクト内のすべての参照について名前を変更するかどうかをたずねるメッセージ ボックスが開いたら、[はい] をクリックします。

  3. コード エディターで SkewButton.cs または SkewButton.vb を開きます。

  4. 自動的に生成されたコードを次のコードで置き換えます。 SkewButton カスタム コントロールは、Button からの継承で、ボタンがデザイナーに表示されると、"Design mode active" というテキストを表示します。 GetIsInDesignMode チェックおよび次のデザイン時コードはオプションであり、デモンストレーションのためだけに示されています。

    Imports System
    Imports System.Collections.Generic
    Imports System.Text
    Imports System.Windows.Controls
    Imports System.Windows.Media
    Imports System.ComponentModel
    
    
    ' The SkewButton control implements a button
    ' with a skew transformation applied.
    Public Class SkewButton
        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 SkewButtonLibrary
    {
        // The SkewButton control implements a button
        // with a skew transformation applied.
        public class SkewButton : Button
        {
            public SkewButton()
            {   
                // 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";
                }
            }
        }
    }
    
  5. プロジェクトの出力パスを "bin\" に設定します。

  6. ソリューションをビルドします。

デザイン時メタデータ アセンブリの作成

デザイン時コードは、特殊なメタデータ アセンブリに配置されます。 このチュートリアルでは、カスタム装飾は、SkewButtonLibrary.VisualStudio.Design という名前のアセンブリに配置されます。 詳細については、「デザイン時メタデータの提供」を参照してください。

デザイン時メタデータ アセンブリを作成するには

  1. Visual Basic または Visual C# の SkewButtonLibrary.VisualStudio.Design という名前の新しいクラス ライブラリ プロジェクトをソリューションに追加します。

  2. プロジェクトの出力パスを ".. \SkewButtonLibrary\bin\" に設定します。 これにより、コントロールのアセンブリとメタデータのアセンブリが同じフォルダー内に配置されるため、デザイナーがメタデータを検出できます。

  3. 次の WPF アセンブリへの参照を追加します。

    • PresentationCore

    • PresentationFramework

    • System.Xaml

    • WindowsBase

  4. 次の WPF デザイナー アセンブリへの参照を追加します。

    • Microsoft.Windows.Design.Extensibility

    • Microsoft.Windows.Design.Interaction

  5. SkewButtonLibrary プロジェクトへの参照を追加します。

  6. ソリューション エクスプローラーで、Class1 コード ファイル名を Metadata.cs または Metadata.vb に変更します。 このプロジェクト内のすべての参照について名前を変更するかどうかをたずねるメッセージ ボックスが開いたら、[はい] をクリックします。

  7. 自動的に生成されたコードを次のコードで置き換えます。 このコードにより、カスタム デザイン時実装を SkewButton クラスに関連付ける 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 Microsoft.Windows.Design.Features
    Imports Microsoft.Windows.Design.Metadata
    Imports SkewButtonLibrary.VisualStudio.Design
    
    Imports SkewButtonLibrary
    
    ' The ProvideMetadata assembly-level attribute indicates to designers
    ' that this assembly contains a class that provides an attribute table. 
    <Assembly: ProvideMetadata(GetType(SkewButtonLibrary.VisualStudio.Design.Metadata))> 
    
    ' Container for any general design-time metadata to initialize.
    ' Designers look for a type in the design-time assembly that 
    ' implements IProvideAttributeTable. If found, designers instantiate
    ' this class and access its AttributeTable property automatically.
    Friend Class Metadata
        Implements IProvideAttributeTable
    
        ' Accessed by the designer to register any design-time metadata.
        Public ReadOnly Property AttributeTable() As AttributeTable _
            Implements IProvideAttributeTable.AttributeTable
            Get
                Dim builder As New AttributeTableBuilder()
    
                ' Add the adorner provider to the design-time metadata.
                builder.AddCustomAttributes( _
                    GetType(SkewButton), _
                    New FeatureAttribute(GetType(SkewButtonAdornerProvider)))
    
                Return builder.CreateTable()
            End Get
        End Property
    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 SkewButtonLibrary;
    using Microsoft.Windows.Design.Features;
    using Microsoft.Windows.Design.Metadata;
    using SkewButtonLibrary.VisualStudio.Design;
    
    [assembly: ProvideMetadata(typeof(SkewButtonLibrary.VisualStudio.Design.Metadata))]
    namespace SkewButtonLibrary.VisualStudio.Design
    {
        // Container for any general design-time metadata to initialize.
        // Designers look for a type in the design-time assembly that 
        // implements IProvideAttributeTable. If found, designers instantiate 
        // this class and access its AttributeTable property automatically.
        internal class Metadata : IProvideAttributeTable
        {
            // Accessed by the designer to register any design-time metadata.
            public AttributeTable AttributeTable
            {
                get
                {
                    AttributeTableBuilder builder = new AttributeTableBuilder();
    
                    // Add the adorner provider to the design-time metadata.
                    builder.AddCustomAttributes(
                        typeof(SkewButton),
                        new FeatureAttribute(typeof(SkewButtonAdornerProvider)));
    
                    return builder.CreateTable();
                }
            }
        }
    }
    
  8. ソリューションを保存します。

装飾プロバイダーの実装

装飾プロバイダーは SkewButtonAdornerProvider という名前の型で実装されます。 この装飾 FeatureProvider により、コントロールの RenderTransform プロパティをデザイン時に設定できるようになります。

装飾プロバイダーを実装するには

  1. SkewButtonAdornerProvider という名前の新しいクラスを SkewButtonLibrary.VisualStudio.Design プロジェクトに追加します。

  2. SkewButtonAdornerProvider のコード エディターで、自動的に生成されたコードを次のコードに置き換えます。 このコードにより、カスタム装飾を提供する 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 
    ' SkewButton control. The adorner is a slider control, which 
    ' changes the SkewTransform of the SkewButton along the x-axis. 
    ' The adorner is placed inside the adorned control.
    Class SkewButtonAdornerProvider
        Inherits PrimarySelectionAdornerProvider
        Private adornedControlModel As ModelItem
        Private batchedChange As ModelEditingScope
        Private skewSlider As Slider
        Private skewSliderAdornerPanel As AdornerPanel
    
        Public Sub New() 
            skewSlider = New Slider()
        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 SkewButton.
        Protected Overrides Sub Activate(ByVal item As ModelItem)
            ' 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
    
            ' Setup the slider's min and max values.
            skewSlider.Minimum = 0
            skewSlider.Maximum = 45
    
            ' Set the slider's background to the rail fill color.
            skewSlider.Background = AdornerColors.RailFillBrush
    
            ' All adorners are placed in an AdornerPanel
            ' for sizing and layout support.
            Dim panel As AdornerPanel = Me.Panel
    
            ' Position the slider as a rail inside the custom control.
            AdornerPanel.SetAdornerHorizontalAlignment(skewSlider, AdornerHorizontalAlignment.Stretch)
            AdornerPanel.SetAdornerVerticalAlignment(skewSlider, AdornerVerticalAlignment.Top)
            AdornerPanel.SetAdornerMargin(skewSlider, New Thickness(5, 5, 5, 0))
    
            ' Initialize the slider when it is loaded.
            AddHandler skewSlider.Loaded, AddressOf slider_Loaded
    
            ' Handle the value changes of the slider control.
            AddHandler skewSlider.ValueChanged, AddressOf slider_ValueChanged
    
            AddHandler skewSlider.PreviewMouseLeftButtonUp, AddressOf slider_MouseLeftButtonUp
    
            AddHandler skewSlider.PreviewMouseLeftButtonDown, AddressOf slider_MouseLeftButtonDown
    
            ' Run the base implementation.
            MyBase.Activate(item)
    
        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.skewSliderAdornerPanel Is Nothing Then
                    Me.skewSliderAdornerPanel = New AdornerPanel()
    
                    ' Add the adorner to the adorner panel.
                    Me.skewSliderAdornerPanel.Children.Add(skewSlider)
    
                    ' Add the panel to the Adorners collection.
                    Adorners.Add(skewSliderAdornerPanel)
                End If
    
                Return Me.skewSliderAdornerPanel
            End Get
        End Property
    
        ' 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 Loaded event.
        ' It assigns the slider control's initial value.
        Sub slider_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs) 
            skewSlider.Value = GetCurrentSkewAngle()
    
        End Sub
    
    
        ' The following method handles the PropertyChanged event.
        ' It updates the slider control's value if the SkewButton control's 
        ' RenderTransform property changed.
        Sub AdornedControlModel_PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) 
            If e.PropertyName = "RenderTransform" Then
                ' Assign the SkewButton control's skew angle to the slider.
                skewSlider.Value = GetCurrentSkewAngle()
            End If
    
        End Sub
    
    
        ' The following method handles the MouseLeftButtonDown event.
        ' It calls the BeginEdit method on the ModelItem which represents the
        ' Skewcontrol.
        Sub slider_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) 
            batchedChange = adornedControlModel.BeginEdit()
    
        End Sub
    
    
        ' The following method handles the MouseLeftButtonUp event.
        ' It commits any changes made to the ModelItem which represents the
        ' Skewcontrol.
        Sub slider_MouseLeftButtonUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) 
            If Not (batchedChange Is Nothing) Then
                batchedChange.Complete()
                batchedChange.Dispose()
                batchedChange = Nothing
            End If
    
        End Sub
    
    
        ' The following method handles the slider control's 
        ' ValueChanged event. It sets the value of the 
        ' RenderTransform property by using the ModelProperty
        ' type.
        Sub slider_ValueChanged(ByVal sender As Object, ByVal e As RoutedPropertyChangedEventArgs(Of Double))
    
            Dim newSkewValue As Double = e.NewValue
    
            ' During setup, don't make a value local and set the skew angle.
            If newSkewValue = GetCurrentSkewAngle() Then
                Return
            End If
    
            ' Access the SkewButton control's RenderTransform property
            ' by using the ModelProperty type.
            Dim skewProperty As ModelProperty = adornedControlModel.Properties("RenderTransform")
    
            If Not skewProperty.IsSet Then
                ' If the value isn't local, make it local 
                ' before setting a sub-property value.
                skewProperty.SetValue(skewProperty.ComputedValue)
            End If
    
            ' Set the RenderTransform property on the SkewButton.
            skewProperty.SetValue(New SkewTransform(newSkewValue, 0))
    
        End Sub
    
        ' This utility method gets the SkewControl control's
        ' skew angle by using the ModelItem.
        Private Function GetCurrentSkewAngle()
            Dim skewXform As SkewTransform = adornedControlModel.Properties("RenderTransform").ComputedValue
            Return skewXform.AngleX
        End Function
    
    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 SkewButtonLibrary.VisualStudio.Design
    {
        // The following class implements an adorner provider for the 
        // SkewButton control. The adorner is a slider control, which 
        // changes the SkewTransform of the SkewButton along the x-axis. 
        // The adorner is placed inside the adorned control.
        class SkewButtonAdornerProvider : PrimarySelectionAdornerProvider
        {
            private ModelItem adornedControlModel;
            private ModelEditingScope batchedChange;
            private Slider skewSlider;
            private AdornerPanel skewButtonAdornerPanel;
    
            public SkewButtonAdornerProvider()
            {
                skewSlider = new Slider();
            }
    
            // 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 SkewButton.
            protected override void Activate(ModelItem item)
            {
                // 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);
    
                // Setup the slider's min and max values.
                skewSlider.Minimum = 0;
                skewSlider.Maximum = 45;
    
                // Set the slider's background to the rail fill color.
                skewSlider.Background = AdornerColors.RailFillBrush;
    
                // All adorners are placed in an AdornerPanel
                // for sizing and layout support.
                AdornerPanel panel = this.Panel;
    
                AdornerPanel.SetAdornerHorizontalAlignment(skewSlider, AdornerHorizontalAlignment.Stretch);
                AdornerPanel.SetAdornerVerticalAlignment(skewSlider, AdornerVerticalAlignment.Top);
                AdornerPanel.SetAdornerMargin(skewSlider, new Thickness(5, 5, 5, 0));
    
                // Initialize the slider when it is loaded.
                skewSlider.Loaded += new RoutedEventHandler(slider_Loaded);
    
                // Handle the value changes of the slider control.
                skewSlider.ValueChanged += 
                    new RoutedPropertyChangedEventHandler<double>(
                        slider_ValueChanged);
    
                skewSlider.PreviewMouseLeftButtonUp += 
                    new System.Windows.Input.MouseButtonEventHandler(
                        slider_MouseLeftButtonUp);
    
                skewSlider.PreviewMouseLeftButtonDown += 
                    new System.Windows.Input.MouseButtonEventHandler(
                        slider_MouseLeftButtonDown);
    
                // Run the base implementation.
                base.Activate(item);
            }
    
            // The Panel utility property demand-creates the 
            // adorner panel and adds it to the provider's 
            // Adorners collection.
            public AdornerPanel Panel
            {
                get
                {
                    if (this.skewButtonAdornerPanel == null)
                    {
                        skewButtonAdornerPanel = new AdornerPanel();
    
                        skewButtonAdornerPanel.Children.Add(skewSlider);
    
                        // Add the panel to the Adorners collection.
                        Adorners.Add(skewButtonAdornerPanel);
                    }
    
                    return this.skewButtonAdornerPanel;
                }
            }
    
            // 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 Loaded event.
            // It assigns the slider control's initial value.
            void slider_Loaded(object sender, RoutedEventArgs e)
            {   
                skewSlider.Value = GetCurrentSkewAngle();
            }
    
            // The following method handles the PropertyChanged event.
            // It updates the slider control's value if the SkewButton control's 
            // RenderTransform property changed.
            void AdornedControlModel_PropertyChanged(
                object sender, 
                System.ComponentModel.PropertyChangedEventArgs e)
            {
                if (e.PropertyName == "RenderTransform")
                {
                    // Assign the SkewButton control's skew angle to the slider.
                    skewSlider.Value = GetCurrentSkewAngle();
                }
            }
    
            // The following method handles the MouseLeftButtonDown event.
            // It calls the BeginEdit method on the ModelItem which represents the
            // Skewcontrol.
            void slider_MouseLeftButtonDown(
                object sender, 
                System.Windows.Input.MouseButtonEventArgs e)
            {
                batchedChange = adornedControlModel.BeginEdit();
            }
    
            // The following method handles the MouseLeftButtonUp event.
            // It commits any changes made to the ModelItem which represents the
            // Skewcontrol.
            void slider_MouseLeftButtonUp(
                object sender, 
                System.Windows.Input.MouseButtonEventArgs e)
            {
                if (batchedChange != null)
                {
                    batchedChange.Complete();
                    batchedChange.Dispose();
                    batchedChange = null;
                }
            }
    
            // The following method handles the slider control's 
            // ValueChanged event. It sets the value of the 
            // RenderTransform property by using the ModelProperty
            // type.
            void slider_ValueChanged(
                object sender, 
                RoutedPropertyChangedEventArgs<double> e)
            {
                double newSkewValue = e.NewValue;
    
                // During setup, don't make a value local and set the skew angle.
                if (newSkewValue == GetCurrentSkewAngle())
                {
                    return;
                }
    
                // Access the SkewButton control's RenderTransform property
                // by using the ModelProperty type.
                ModelProperty skewProperty = 
                    adornedControlModel.Properties["RenderTransform"];
    
                if (!skewProperty.IsSet)
                {
                    // If the value isn't local, make it local 
                    // before setting a sub-property value.
                    skewProperty.SetValue(skewProperty.ComputedValue);
                }
    
                // Set the RenderTransform property on the SkewButton.
                skewProperty.SetValue(new SkewTransform(newSkewValue, 0));
            }
    
            // This utility method gets the SkewControl control's
            // skew angle by using the ModelItem.
            private double GetCurrentSkewAngle()
            {   
                SkewTransform skewXform = adornedControlModel.Properties[
                    "RenderTransform"].ComputedValue as SkewTransform;
    
                return skewXform.AngleX;
            }
        }
    }
    
  3. ソリューションをビルドします。

デザイン時実装のテスト

SkewButton コントロールは、他の WPF コントロールと同じように使用できます。 WPF デザイナーは、すべてのデザイン時オブジェクトの作成を処理します。

デザイン時実装をテストするには

  1. DemoApplication という名前の新しい WPF アプリケーション プロジェクトをソリューションに追加します。

    WPF デザイナーで MainWindow.xaml が開きます。

  2. SkewButtonLibrary プロジェクトへの参照を追加します。

  3. XAML ビューで、自動的に生成された XAML を次の XAML に置き換えます。 この XAML により、SkewButtonLibrary 名前空間への参照が追加され、SkewButton カスタム コントロールが追加されます。 ボタンは、"Design mode active" というテキストと共にデザイン ビューに表示されます。これは、現在デザイン モードであることを示すものです。 ボタンが表示されない場合は、デザイナーの一番上の情報バーをクリックして、ビューの再読み込みを行う必要があります。

    <Window x:Class="DemoApplication.MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:cc="clr-namespace:SkewButtonLibrary;assembly=SkewButtonLibrary"
        Title="Window1" Height="300" Width="300">
        <Grid>
            <cc:SkewButton Margin="30,30,30,30" Background="#FFD4D0C8">
                <cc:SkewButton.RenderTransform>
                    <SkewTransform AngleX="0" AngleY="0" />
                </cc:SkewButton.RenderTransform>
            </cc:SkewButton>
        </Grid>
    </Window>
    
  4. デザイン ビューで、SkewButton コントロールをクリックして選択します。

    Slider コントロールが SkewButton コントロール内に表示されます。 スライダー コントロールが表示されない場合は、ソリューションのリビルドを試みます。

  5. スライダー コントロールの値を変更します。

    スライダーをドラッグすると、コントロールが傾斜します。 XAML ビューで、RenderTransform プロパティが、装飾によって指定された値に設定されます。

  6. DemoApplication プロジェクトを実行します。

    実行時には、装飾で設定した角度でボタンが傾斜されます。

次の手順

カスタム コントロールに、さらにカスタム デザイン時機能を追加できます。

参照

参照

PrimarySelectionAdornerProvider

SkewTransform

その他の技術情報

WPF Designer Extensibility Samples (WPF デザイナーの機能拡張のサンプル)

高度な機能拡張という概念

WPF デザイナーの機能拡張