演练:创建设计时装饰器

本演练演示如何为 Windows Presentation Foundation (WPF) 自定义控件创建设计时装饰器。 可以使用 适用于 Visual Studio 的 WPF 设计器中的设计时装饰器,针对自定义按钮控件设置 Opacity 属性的值。 本演练中的控件是一个简单的按钮,装饰器是一个用来更改按钮不透明度的滑块。 有关完整的代码清单,请参见 WPF Designer Extensibility Samples(WPF 设计器扩展性示例)站点上的“Opacity Slider Adorner”(不透明滑块装饰器)示例。

在本演练中,您将执行下列任务:

  • 创建一个 WPF 自定义控件库项目。

  • 为设计时元数据创建一个单独的程序集。

  • 实现装饰器提供程序。

  • 在设计时测试控件。

完成本演练后,您将知道如何为自定义控件创建装饰器提供程序。

提示

显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您现用的设置或版本。 若要更改设置,请在“工具”菜单上选择“导入和导出设置”。 有关更多信息,请参见 使用设置

系统必备

您需要以下组件来完成本演练:

  • Visual Studio 2010.

创建自定义控件

第一步是为自定义控件创建项目。 该控件是一个带有少量设计时代码的简单按钮,该按钮使用 GetIsInDesignMode 方法来实现设计时行为。

创建自定义控件

  1. 使用 Visual Basic 或 Visual C# 创建一个名为 CustomControlLibrary 的新 WPF 自定义控件库项目。

    CustomControl1 的代码在“代码编辑器”中打开。

  2. 在**“解决方案资源管理器”中,将代码文件的名称更改为 ButtonWithDesignTime.cs 或 ButtonWithDesignTime.vb。 如果出现消息框,询问是否对此项目中的所有引用执行重命名操作,请单击“是”**。

  3. 在“代码编辑器”中打开 ButtonWithDesignTime.cs 或 ButtonWithDesignTime.vb。

  4. 用下面的代码替换自动生成的代码。 ButtonWithDesignTime 自定义控件继承自 Button,当按钮出现在设计器中时,该控件将显示文本“已激活设计模式”。 GetIsInDesignMode 检查和下面的设计时代码均为可选,仅用作演示。

    Imports System
    Imports System.Collections.Generic
    Imports System.Text
    Imports System.Windows.Controls
    Imports System.Windows.Media
    Imports System.ComponentModel
    
    Public Class ButtonWithDesignTime
        Inherits Button
    
        Public Sub New()
            ' 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 CustomControlLibrary
    {
        public class ButtonWithDesignTime : Button
        {
            public ButtonWithDesignTime()
            {
                // 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. 生成解决方案。

创建设计时元数据程序集

设计时代码在特定元数据程序集中部署。 对于本演练,自定义装饰器仅受 Visual Studio 支持,在名为 CustomControlLibrary.VisualStudio.Design 的程序集中部署。 有关更多信息,请参见提供设计时元数据

创建设计时元数据程序集

  1. 使用 Visual Basic 或 Visual C# 为解决方案添加一个名为 CustomControlLibrary.VisualStudio.Design 的新类库项目。

  2. 将项目的输出路径设置为“.. \CustomControlLibrary\bin\”。 这样可使控件的程序集与元数据程序集位于同一文件夹中,从而可为设计器启用元数据发现。

  3. 添加对下列 WPF 程序集的引用。

    • PresentationCore

    • PresentationFramework

    • System.Xaml

    • WindowsBase

  4. 添加对下列 WPF 设计器程序集的引用。

    • Microsoft.Windows.Design.Extensibility

    • Microsoft.Windows.Design.Interaction

  5. 添加对 CustomControlLibrary 项目的引用。

  6. 在**“解决方案资源管理器”**中,将 Class1 代码文件的名称更改为 Metadata.cs 或 Metadata.vb。

  7. 用下面的代码替换自动生成的代码。 此代码将创建一个将自定义设计时实现附加到 ButtonWithDesignTime 类的 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 CustomControlLibrary
    Imports Microsoft.Windows.Design.Features
    Imports Microsoft.Windows.Design.Metadata
    
    ' The ProvideMetadata assembly-level attribute indicates to designers
    ' that this assembly contains a class that provides an attribute table. 
    <Assembly: ProvideMetadata(GetType(CustomControlLibrary.VisualStudio.Design.Metadata))> 
    
    Namespace CustomControlLibrary.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.
        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(ButtonWithDesignTime), _
                                                New FeatureAttribute(GetType(OpacitySliderAdornerProvider)))
    
                    Return builder.CreateTable()
                End Get
            End Property
    
    
        End Class
    
    End Namespace
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ComponentModel;
    using System.Windows.Media;
    using System.Windows.Controls;
    using System.Windows;
    
    using CustomControlLibrary;
    using Microsoft.Windows.Design.Features;
    using Microsoft.Windows.Design.Metadata;
    
    // The ProvideMetadata assembly-level attribute indicates to designers
    // that this assembly contains a class that provides an attribute table. 
    [assembly: ProvideMetadata(typeof(CustomControlLibrary.VisualStudio.Design.Metadata))]
    namespace CustomControlLibrary.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(ButtonWithDesignTime),
                        new FeatureAttribute(typeof(OpacitySliderAdornerProvider)));
    
                    return builder.CreateTable();
                }
            }
        }
    }
    
  8. 保存解决方案。

实现装饰器提供程序

装饰器提供程序是在名为 OpacitySliderAdornerProvider 的类型中实现的。 此装饰器允许用户在设计时设置控件的 Opacity 属性。

实现装饰器提供程序

  1. 向 CustomControlLibrary.VisualStudio.Design 项目中添加一个名为 OpacitySliderAdornerProvider 的新类。

  2. 在 OpacitySliderAdornerProvider 的代码编辑器中,用下面的代码替换自动生成的代码。 此代码实现的 PrimarySelectionAdornerProvider 提供一个基于 Slider 控件的装饰器。

    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
    
    Namespace CustomControlLibrary.VisualStudio.Design
    
        ' The following class implements an adorner provider for the 
        ' adorned control. The adorner is a slider control, which 
        ' changes the Background opacity of the adorned control.
        Class OpacitySliderAdornerProvider
            Inherits PrimarySelectionAdornerProvider
            Private adornedControlModel As ModelItem
            Private batchedChange As ModelEditingScope
            Private opacitySlider As Slider
            Private opacitySliderAdornerPanel As AdornerPanel
    
            Public Sub New()
                opacitySlider = 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 adorned control.
            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.
                opacitySlider.Minimum = 0
                opacitySlider.Maximum = 1
    
                ' Setup the adorner panel.
                ' All adorners are placed in an AdornerPanel
                ' for sizing and layout support.
                Dim myPanel = Me.Panel
    
                ' The slider extends the full width of the control it adorns.
                AdornerPanel.SetAdornerHorizontalAlignment( _
                    opacitySlider, _
                    AdornerHorizontalAlignment.Stretch)
    
                ' Position the adorner above the control it adorns.
                AdornerPanel.SetAdornerVerticalAlignment( _
                    opacitySlider, _
                    AdornerVerticalAlignment.OutsideTop)
    
                ' Position the adorner 5 pixels above the control. 
                AdornerPanel.SetAdornerMargin( _
                    opacitySlider, _
                    New Thickness(0, 0, 0, 5))
    
                ' Initialize the slider when it is loaded.
                AddHandler opacitySlider.Loaded, AddressOf slider_Loaded
    
                ' Handle the value changes of the slider control.
                AddHandler opacitySlider.ValueChanged, AddressOf slider_ValueChanged
    
                AddHandler opacitySlider.PreviewMouseLeftButtonUp, _
                    AddressOf slider_MouseLeftButtonUp
    
                AddHandler opacitySlider.PreviewMouseLeftButtonDown, _
                    AddressOf slider_MouseLeftButtonDown
    
                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.opacitySliderAdornerPanel Is Nothing Then
                        Me.opacitySliderAdornerPanel = New AdornerPanel()
    
                        ' Add the adorner to the adorner panel.
                        Me.opacitySliderAdornerPanel.Children.Add(opacitySlider)
    
                        ' Add the panel to the Adorners collection.
                        Adorners.Add(opacitySliderAdornerPanel)
                    End If
    
                    Return Me.opacitySliderAdornerPanel
                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 PropertyChanged event.
            ' It updates the slider control's value if the adorned control's 
            ' Background property changed,
            Sub AdornedControlModel_PropertyChanged( _
                ByVal sender As Object, _
                ByVal e As System.ComponentModel.PropertyChangedEventArgs)
    
                If e.PropertyName = "Background" Then
                    opacitySlider.Value = GetCurrentOpacity()
                End If
    
            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)
    
                opacitySlider.Value = GetCurrentOpacity()
    
            End Sub
    
            ' The following method handles the MouseLeftButtonDown event.
            ' It calls the BeginEdit method on the ModelItem which represents 
            ' the adorned control.
            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
            ' the adorned control.
            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 
            ' Background opacity by using the ModelProperty type.
            Sub slider_ValueChanged( _
                ByVal sender As Object, _
                ByVal e As RoutedPropertyChangedEventArgs(Of Double))
    
                If (True) Then
                    Dim newOpacityValue As Double = e.NewValue
    
                    ' During setup, don't make a value local and set the opacity.
                    If newOpacityValue = GetCurrentOpacity() Then
                        Return
                    End If
    
                    ' Access the adorned control's Background property
                    ' by using the ModelProperty type.
                    Dim backgroundProperty As ModelProperty = _
                        adornedControlModel.Properties("Background")
                    If Not backgroundProperty.IsSet Then
                        ' If the value isn't local, make it local 
                        ' before setting a sub-property value.
                        backgroundProperty.SetValue(backgroundProperty.ComputedValue)
                    End If
    
                    ' Set the Opacity property on the Background Brush.
                    backgroundProperty.Value.Properties("Opacity").SetValue(newOpacityValue)
                End If
            End Sub
    
            ' This utility method gets the adorned control's
            ' Background brush by using the ModelItem.
            Function GetCurrentOpacity() As Double
    
                Dim backgroundBrushComputedValue As Brush = _
                CType(adornedControlModel.Properties("Background").ComputedValue,  _
                Brush)
    
                Return backgroundBrushComputedValue.Opacity
    
            End Function
        End Class
    End Namespace
    
    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 CustomControlLibrary.VisualStudio.Design
    {
        // The following class implements an adorner provider for the 
        // adorned control. The adorner is a slider control, which 
        // changes the Background opacity of the adorned control.
        class OpacitySliderAdornerProvider : PrimarySelectionAdornerProvider
        {
            private ModelItem adornedControlModel;
            private ModelEditingScope batchedChange;
            private Slider opacitySlider;
            private AdornerPanel opacitySliderAdornerPanel;
    
            public OpacitySliderAdornerProvider()
            {
                opacitySlider = 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 adorned control.
            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.
                opacitySlider.Minimum = 0;
                opacitySlider.Maximum = 1;
    
                // Setup the adorner panel.
                // All adorners are placed in an AdornerPanel
                // for sizing and layout support.
                AdornerPanel myPanel = this.Panel;
    
                // The slider extends the full width of the control it adorns.
                AdornerPanel.SetAdornerHorizontalAlignment( 
                    opacitySlider, 
                    AdornerHorizontalAlignment.Stretch);
    
                // Position the adorner above the control it adorns.
                AdornerPanel.SetAdornerVerticalAlignment(
                    opacitySlider, 
                    AdornerVerticalAlignment.OutsideTop);
    
                // Position the adorner 5 pixels above the control. 
                AdornerPanel.SetAdornerMargin(
                    opacitySlider, 
                    new Thickness(0, 0, 0, 5));
    
                // Initialize the slider when it is loaded.
                opacitySlider.Loaded += new RoutedEventHandler(slider_Loaded);
    
                // Handle the value changes of the slider control.
                opacitySlider.ValueChanged += 
                    new RoutedPropertyChangedEventHandler<double>(
                        slider_ValueChanged);
    
                opacitySlider.PreviewMouseLeftButtonUp += 
                    new System.Windows.Input.MouseButtonEventHandler(
                        slider_MouseLeftButtonUp);
    
                opacitySlider.PreviewMouseLeftButtonDown += 
                    new System.Windows.Input.MouseButtonEventHandler(
                        slider_MouseLeftButtonDown);
    
                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.opacitySliderAdornerPanel == null)
                    {
                        opacitySliderAdornerPanel = new AdornerPanel();
    
                        opacitySliderAdornerPanel.Children.Add(opacitySlider);
    
                        // Add the panel to the Adorners collection.
                        Adorners.Add(opacitySliderAdornerPanel);
                    }
    
                    return this.opacitySliderAdornerPanel;
                } 
            }
    
    
            // 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.
            // It updates the slider control's value if the adorned control's 
            // Background property changed,
            void AdornedControlModel_PropertyChanged(
                object sender, 
                System.ComponentModel.PropertyChangedEventArgs e)
            {
                if (e.PropertyName == "Background")
                {   
                    opacitySlider.Value = GetCurrentOpacity();
                }
            }
    
            // The following method handles the Loaded event.
            // It assigns the slider control's initial value.
            void slider_Loaded(object sender, RoutedEventArgs e)
            {   
                opacitySlider.Value = GetCurrentOpacity();
            }
    
            // The following method handles the MouseLeftButtonDown event.
            // It calls the BeginEdit method on the ModelItem which represents 
            // the adorned control.
            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
            // the adorned control.
            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 
            // Background opacity by using the ModelProperty type.
            void slider_ValueChanged(
                object sender, 
                RoutedPropertyChangedEventArgs<double> e)
            {
                double newOpacityValue = e.NewValue;
    
                // During setup, don't make a value local and set the opacity.
                if (newOpacityValue == GetCurrentOpacity())
                {
                    return;
                }
    
                // Access the adorned control's Background property
                // by using the ModelProperty type.
                ModelProperty backgroundProperty = 
                    adornedControlModel.Properties["Background"];
                if (!backgroundProperty.IsSet)
                {
                    // If the value isn't local, make it local 
                    // before setting a sub-property value.
                    backgroundProperty.SetValue(backgroundProperty.ComputedValue);
                }
    
                // Set the Opacity property on the Background Brush.
                backgroundProperty.Value.Properties["Opacity"].SetValue(newOpacityValue);
            }
    
            // This utility method gets the adorned control's
            // Background brush by using the ModelItem.
            private double GetCurrentOpacity()
            {
                Brush backgroundBrushComputedValue =
                    (Brush)adornedControlModel.Properties["Background"].ComputedValue;
    
                return backgroundBrushComputedValue.Opacity;
            }
        }
    }
    
  3. 生成解决方案。

测试设计时实现

可以像使用任何其他 WPF 控件一样使用 ButtonWithDesignTime 控件。 WPF 设计器处理所有设计时对象的创建。

测试设计时实现

  1. 使用 Visual Basic 或 Visual C# 为解决方案添加一个名为 DemoApplication 的新 WPF 应用程序项目。

    MainWindow.xaml 将在 WPF 设计器中打开。

  2. 添加对 CustomControlLibrary 项目的引用。

  3. 在 XAML 视图中,用以下 XAML 替换自动生成的 XAML。 此 XAML 将添加对 CustomControlLibrary 命名空间的引用并添加 ButtonWithDesignTime 自定义控件。 该按钮出现在“设计”视图中,并显示文本“已激活设计模式”,表明该按钮处于设计模式下。 如果该按钮未出现,则可能需要单击设计器顶部的信息栏以重新加载视图。

    <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:CustomControlLibrary;assembly=CustomControlLibrary"
        Title="Window1" Height="300" Width="300">
        <Grid>
            <cc:ButtonWithDesignTime Margin="30,30,30,30" Background="#FFD4D0C8"></cc:ButtonWithDesignTime>
        </Grid>
    </Window>
    
  4. 在设计视图中,单击 ButtonWithDesignTime 控件将其选中。

    将在 ButtonWithDesignTime 控件上方出现一个 Slider 控件。

  5. 使用滑块控件装饰器更改按钮的不透明度。

    在 XAML 视图中,Opacity 属性将设置为 Slider 控件指定的值。

  6. 运行 DemoApplication 项目。

    在运行时,该按钮具有您用装饰器设置的不透明度。

后续步骤

您可以向自定义控件中添加更多设计时功能。

请参见

参考

PrimarySelectionAdornerProvider

其他资源

WPF Designer Extensibility Samples

高级扩展性概念

WPF 设计器扩展性

提供设计时元数据