次の方法で共有


チュートリアル : カラー エディターの実装

WPF Designer for Visual Studio の機能拡張モデルを使用すると、[プロパティ] ウィンドウ内のプロパティを操作するためのカスタムの値エディターをデザイン時に作成できます。 作成できるのは、インライン エディターまたは拡張エディターです。インライン エディターは、[プロパティ] ウィンドウで値を直接編集できるエディターです。拡張エディターは、[プロパティ] ウィンドウの外部でプロパティを編集する UI を備えたエディターです。 拡張エディターを作成する方法を示すために、このチュートリアルでは、コントロールの Background プロパティを操作するためのカラー エディターを作成する手順を説明します。この拡張エディターは、[プロパティ] ウィンドウのインライン エディターから開かれます。

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

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

  • 拡張エディターとして動作するユーザー コントロールを作成する。

  • [プロパティ] ウィンドウのプロパティ値を編集したり拡張エディターを開いたりするために使用できるインライン エディターを作成する。

  • カスタム エディターを提供するクラスにエディターを接続するために使用する ExtendedPropertyValueEditor 派生クラスを作成する。

  • 新しい拡張エディターを登録するために IProvideAttributeTable インターフェイスを実装するクラスを作成する。

  • デザイン時に拡張エディターをテストする。

必須コンポーネント

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

  • Visual Studio 2010.

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

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

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

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

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

  2. CustomControl1 のコード エディターで、CustomControlLibrary 名前空間のコードを次のコードに置き換えます。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace CustomControlLibrary
    {
        public class CustomControl1 : Button
        {
            public CustomControl1()
            {
                if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
                {
                    Background = Brushes.Red;
                }
            }
        }
    }
    
  3. プロジェクトの出力パスを "bin\" に設定します。

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

拡張エディターのユーザー コントロールの作成

前の手順で作成したコントロールは、カスタムのカラー エディターのアタッチ先となるコントロールです。 この手順では、拡張エディターとして動作する別のユーザー コントロールを作成します。

拡張エディターとして動作するユーザー コントロールを作成するには

  1. Visual C# で CustomControlLibrary.Design という名前の新しい WPF カスタム コントロール ライブラリ プロジェクトをソリューションに追加します。

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

  2. ソリューション エクスプローラーで、CustomControl1 ファイルを CustomControlLibrary.Design プロジェクトから削除します。

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

    • Microsoft.Windows.Design.Extensibility

    • Microsoft.Windows.Design.Interaction

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

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

  6. ColorsList という名前の新しいクラスを CustomControlLibrary.Design プロジェクトに追加します。

  7. ColorsList のコード エディターで、自動的に生成されたコードを次のコードに置き換えます。

    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Media;
    using System.Reflection;
    using System.Collections.ObjectModel;
    
    namespace CustomControlLibrary.Design
    {
        public class ColorsList : ObservableCollection<Color>
        {
            public ColorsList()
            {
                Type type = typeof(Colors);
                foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Static))
                {
                    if (propertyInfo.PropertyType == typeof(Color))
                    {
                        Add((Color)propertyInfo.GetValue(null, null));
                    }
                }
            }
        }
    }
    
  8. CustomControlLibrary.Design プロジェクトに ColorsListControl という名前の新しいユーザー コントロール (WPF) を追加します。

    ColorsListControl.xaml のコードがデザイナーで開きます。

  9. ColorsListControl.xaml の XAML ビューで、自動的に生成された XAML を次の XAML に置き換えます。

        <UserControl x:Class="CustomControlLibrary.Design.ColorsListControl"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Local="clr-namespace:CustomControlLibrary.Design" 
        xmlns:PropertyEditing="clr-namespace:Microsoft.Windows.Design.PropertyEditing;assembly=Microsoft.Windows.Design.Interaction"
        Height="184" Width="260" Background="White">
        <UserControl.Resources>
            <Local:ColorsList x:Key="colors"/>
            <Style TargetType="{x:Type Button}">
                <EventSetter Event="Click" Handler="ItemsControl_Click"/>
            </Style>
        </UserControl.Resources>
    
        <ItemsControl 
            ItemsSource="{Binding Source={StaticResource colors}}" 
            HorizontalContentAlignment="Stretch" 
            VerticalContentAlignment="Stretch" 
            HorizontalAlignment="Stretch" 
            VerticalAlignment="Stretch">
            <ItemsControl.Template>
                <ControlTemplate TargetType="ItemsControl">
                    <Border CornerRadius="5" >
                        <WrapPanel Orientation="Horizontal"
                                   VerticalAlignment="Center"
                                   HorizontalAlignment="Center">
                            <ScrollViewer>
                                <ItemsPresenter/>
                            </ScrollViewer>
                        </WrapPanel>
                    </Border>
                </ControlTemplate>
            </ItemsControl.Template>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Tag="{Binding}" Command="{x:Static PropertyEditing:PropertyValueEditorCommands.ShowInlineEditor}">
                        <Button.Template>
                            <ControlTemplate>
                                <Border Width="30" Height="30" BorderBrush="Black" BorderThickness="1" CornerRadius="5">
                                    <Rectangle Width="22" Height="22" ToolTip="{Binding}">
                                        <Rectangle.Fill>
                                            <SolidColorBrush Color="{Binding}"/>
                                        </Rectangle.Fill>
                                    </Rectangle>
                                </Border>
                            </ControlTemplate>
                        </Button.Template>
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </UserControl>
    
  10. ソリューション エクスプローラーで、ColorsListControl.xaml を展開し、ColorsListControl.xaml.cs を開きます。

  11. ColorsListControl のコード エディターで、自動的に生成されたコードを次のコードに置き換えます。

    using System;
    using System.Linq;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace CustomControlLibrary.Design
    {
        public partial class ColorsListControl : System.Windows.Controls.UserControl
        {
            public ColorsListControl()
            {
                InitializeComponent();
            }
    
            public static readonly DependencyProperty SelectedColorProperty = DependencyProperty.Register("SelectedColor", typeof(Color), typeof(ColorsListControl), new FrameworkPropertyMetadata(null));
            public Color SelectedColor
            {
                get { return (Color)base.GetValue(SelectedColorProperty); }
                set { base.SetValue(SelectedColorProperty, value); }
            }
    
            public static readonly DependencyProperty SelectedBrushProperty = DependencyProperty.Register("SelectedBrush", typeof(SolidColorBrush), typeof(ColorsListControl), new FrameworkPropertyMetadata(null));
            public SolidColorBrush SelectedBrush
            {
                get { return (SolidColorBrush)base.GetValue(SelectedBrushProperty); }
                set { base.SetValue(SelectedBrushProperty, value); }
            }
    
            private void ItemsControl_Click(object sender, RoutedEventArgs e)
            {
                SelectedColor = (Color)((Button)sender).Tag;
                SelectedBrush = new SolidColorBrush(SelectedColor);
            }
        }
    }
    
  12. ソリューションをビルドします。

  13. ColorsListControl.xaml をデザイナーに再度読み込みます。拡張エディター UI がデザイン ビューに表示されます。

カラー エディターのテンプレートの作成

カラー エディターのインライン エディターは、拡張エディターほど複雑ではなく、XAML データ テンプレートを使用して作成できます。 また、前の手順で作成したユーザー コントロールを使用するよう指定するデータ テンプレートも拡張エディター用に作成します。

カラー エディターのテンプレートを作成するには

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

  2. EditorResources のコード エディターで、自動的に生成されたコードを次のコードに置き換えます。

    namespace ExtendedEditorNamespace
    {
        using System;
        using System.Collections.Generic;
        using System.Text;
        using System.Windows;
        public partial class EditorResources : ResourceDictionary {
            public EditorResources()
                : base()
            {
                InitializeComponent();
            }
        }
    }
    
  3. [プロジェクト] メニューの [リソース ディクショナリの追加] をクリックします。

  4. フォームに EditorResources.xaml という名前を付け、[追加] をクリックします。

    EditorResources.xaml のコードがデザイナーで開きます。

  5. EditorResources.xaml の XAML ビューで、自動的に生成された XAML を次の XAML に置き換えます。

        <ResourceDictionary
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:PropertyEditing="clr-namespace:Microsoft.Windows.Design.PropertyEditing;assembly=Microsoft.Windows.Design.Interaction"
        xmlns:Local="clr-namespace:CustomControlLibrary.Design"
        xmlns:Media="clr-namespace:System.Windows.Media;assembly=PresentationCore"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        x:Class="CustomControlLibrary.Design.EditorResources">
    
        <DataTemplate x:Key="BrushExtendedEditorTemplate">
            <Local:ColorsListControl SelectedBrush="{Binding Value, Mode=TwoWay}"/>
        </DataTemplate>
    
    
        <DataTemplate x:Key="BrushInlineEditorTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <TextBox Grid.Column="0" Text="{Binding StringValue}"/>
                <PropertyEditing:EditModeSwitchButton Grid.Column="1"/>
            </Grid>
        </DataTemplate>
    
    </ResourceDictionary>
    
  6. ソリューションをビルドします。

テンプレートのカプセル化とエディターの登録

作業は山を越えました。 カラー エディター用の拡張エディター テンプレートとインライン エディター テンプレートの作成が完了したので、これらをカプセル化するクラスを作成し、カスタム コントロールに登録できます。

エディターをカプセル化および登録するには

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

  2. BrushExtendedEditor のコード エディターで、自動的に生成されたコードを次のコードに置き換えます。

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Windows.Design.PropertyEditing;
    using System.Windows;
    
    namespace CustomControlLibrary.Design
    {
        public class BrushExtendedEditor : ExtendedPropertyValueEditor
        {
            private EditorResources res = new EditorResources();
    
            public BrushExtendedEditor()
            {
                this.ExtendedEditorTemplate = res["BrushExtendedEditorTemplate"] as DataTemplate;
                this.InlineEditorTemplate = res["BrushInlineEditorTemplate"] as DataTemplate;
            }
        }
    }
    
  3. Metadata という名前の新しいクラスを CustomControlLibrary.Design プロジェクトに追加します。

  4. Metadata のコード エディターで、自動的に生成されたコードを次のコードに置き換えます。

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Windows.Design.Metadata;
    using System.ComponentModel;
    using Microsoft.Windows.Design.PropertyEditing;
    using System.Windows.Media;
    using System.Windows.Controls;
    using System.Windows;
    using CustomControlLibrary;
    
    // The ProvideMetadata assembly-level attribute indicates to designers
    // that this assembly contains a class that provides an attribute table. 
    [assembly: ProvideMetadata(typeof(CustomControlLibrary.Design.Metadata))]
    
    namespace CustomControlLibrary.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();
    
                    builder.AddCustomAttributes
                        (typeof(CustomControl1),
                        "Background",
                        PropertyValueEditor.CreateEditorAttribute(
                            typeof(BrushExtendedEditor)));
    
                    return builder.CreateTable();
                }
            }
        }
    }
    
  5. ソリューションをビルドします。

カラー エディターのテスト

カラー エディターの作成が完了しました。 後はテストするだけです。 エディターをテストするには、WPF アプリケーション プロジェクトをソリューションに追加し、カスタム コントロールを追加します。 その後、[プロパティ] ウィンドウで背景色を変更し、新しいエディターの動作を確認します。

カラー エディターをテストするには

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

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

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

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

        <Window x:Class="DemoApplication.MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300" xmlns:my="clr-namespace:CustomControlLibrary;assembly=CustomControlLibrary">
        <Grid>
            <my:CustomControl1 Margin="30,30,30,30" Name="customControl11"></my:CustomControl1>
        </Grid>
    </Window>
    
  4. デザイナー ビューでコントロールを選択します。

  5. [プロパティ] ウィンドウで、Background プロパティの横にあるドロップダウン ボタンをクリックします。 既定の色リストの代わりに、ビジュアルなカラー エディターが表示されます。

  6. エディターから色を選択します。 カスタム コントロールの背景が、その色に変更されます。

参照

処理手順

チュートリアル : インライン値エディターの実装

方法 : 値エディターを作成する

その他の技術情報

カスタム エディターの作成

WPF デザイナーの機能拡張