逐步解說:建立設計階段裝飾項
本逐步解說將示範如何為 Windows Presentation Foundation (WPF) 自訂控制項建立設計階段裝飾項。 您可以在 WPF Designer for Visual Studio 中使用這個裝飾項,設定自訂按鈕控制項上的 Opacity 屬性的值。 在這個逐步解說中,控制項是簡單的按鈕,而裝飾項是可讓您變更按鈕不透明度的滑桿。 如需完整的程式碼清單,請參閱 WPF 設計工具擴充性範例網站上的<不透明度滑桿裝飾項>範例 (英文)。
在這個逐步解說中,您會執行下列工作:
建立 WPF 自訂控制項程式庫專案。
為設計階段中繼資料建立個別組件。
實作裝飾項提供者。
在設計階段測試控制項。
完成時,您就知道要如何建立自訂控制項的裝飾項提供者。
注意
根據您目前使用的設定或版本,您所看到的對話方塊與功能表指令可能會與 [說明] 中描述的不同。若要變更設定,請從 [工具] 功能表中選擇 [匯入和匯出設定]。如需詳細資訊,請參閱 Visual Studio 設定。
必要條件
您需要下列元件才能完成此逐步解說:
- Visual Studio 2012 RC.
建立自訂控制項
第一個步驟是為自訂控制項建立專案。 這個控制項是一個具有少量設計階段程式碼的簡易按鈕,這個程式碼使用 GetIsInDesignMode 方法來實作設計階段行為。
建立自訂控制項
在 Visual Basic 或 Visual C# 中建立名為 CustomControlLibrary 的新 WPF 自訂控制項程式庫專案。
CustomControl1 的程式碼隨即在 [程式碼編輯器] 中開啟。
在 [方案總管] 中,將程式碼檔案的名稱變更為 ButtonWithDesignTime.cs 或 ButtonWithDesignTime.vb。 如果顯示訊息方塊詢問您是否要重新命名專案中的所有參考,請按一下 [是]。
在 [程式碼編輯器] 中開啟 ButtonWithDesignTime.cs 或 ButtonWithDesignTime.vb。
以下列程式碼取代自動產生的程式碼。 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"; } } } }
將專案的輸出路徑設定為 "bin\"。
建置方案。
建立設計階段中繼資料組件
設計階段程式碼部署在特殊中繼資料組件中。 在這個逐步解說中,只有 Visual Studio 才支援自訂裝飾項,此自訂裝飾項部署在名為 CustomControlLibrary.VisualStudio.Design 的組件中。 如需詳細資訊,請參閱提供設計階段中繼資料。
若要建立設計階段中繼資料組件
在 Visual Basic 或 Visual C# 中,將名為 CustomControlLibrary.VisualStudio.Design 的新類別庫 (Class Library) 專案加入至方案。
將專案的輸出路徑設定為 ".. \CustomControlLibrary\bin\"。 這麼做會將控制項的組件和中繼資料組件保留在同一個資料夾中,讓設計工具可進行中繼資料探索。
加入下列 WPF 組件的參考。
PresentationCore
PresentationFramework
System.Xaml
WindowsBase
加入下列 WPF Designer組件的參考。
Microsoft.Windows.Design.Extensibility
Microsoft.Windows.Design.Interaction
加入 CustomControlLibrary 專案的參考。
在 [方案總管] 中,將 Class1 程式碼檔案的名稱變更為 Metadata.cs 或 Metadata.vb。
以下列程式碼取代自動產生的程式碼。 這個程式碼會建立 AttributeTable,會將自訂設計階段實作附加至 ButtonWithDesignTime 類別。
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(); } } } }
儲存方案。
實作裝飾項提供者。
裝飾項提供者實作在名為 OpacitySliderAdornerProvider 的型別中。 此裝飾項可讓使用者在設計階段設定控制項的 Opacity 屬性。
若要實作裝飾項提供者
將名為 OpacitySliderAdornerProvider 的新類別,加入至 CustomControlLibrary.VisualStudio.Design 專案。
在 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; } } }
建置方案。
測試設計階段實作
您可以使用 ButtonWithDesignTime 控制項,就像使用任何其他 WPF 控制項一樣。 WPF Designer會負責建立所有的設計階段物件。
若要測試設計階段實作
在 Visual Basic 或 Visual C# 中,將名為 DemoApplication 的新 WPF 應用程式專案加入至方案。
MainWindow.xaml 隨即在 WPF Designer中開啟。
加入 CustomControlLibrary 專案的參考。
在 [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>
按一下 [設計] 檢視中的 ButtonWithDesignTime 控制項選取該項目。
Slider 控制項會出現在 ButtonWithDesignTime 控制項上方。
使用滑桿控制項裝飾項變更按鈕的不透明度。
執行 DemoApplication 專案。
在執行階段,按鈕的不透明度就是您使用裝飾項設定的不透明度。
後續步驟
您可以將多個自訂設計階段功能,加入至自訂控制項。
將 MenuAction 加入到自訂設計階段。 如需詳細資訊,請參閱逐步解說:建立功能表提供者。
建立裝飾項提供者以進行就地編輯 (In-Place Editing)。 如需詳細資訊,請參閱逐步解說:實作就地編輯。
建立您可以在 [屬性] 視窗中使用的自訂色彩編輯器。 如需詳細資訊,請參閱逐步解說:實作色彩編輯器。
請參閱
參考
PrimarySelectionAdornerProvider
概念
其他資源
WPF 設計工具擴充性範例