Procedura dettagliata: implementazione di una sbarra in un controllo
Aggiornamento: novembre 2007
In questa procedura dettagliata viene illustrato come creare uno strumento decorativo di tipo sbarra per un controllo personalizzato WPF (Windows Presentation Foundation). Uno strumento decorativo di tipo sbarra consente di aggiungere un indicatore o righello lungo un lato di un controllo, ma non consente il ridimensionamento in scala lungo un solo asse. Lo strumento decorativo visuale è un dispositivo di scorrimento che viene posizionato all'interno del controllo. È possibile utilizzare questo strumento decorativo per impostare la proprietà RenderTransform su un controllo pulsante personalizzato. L'impostazione della proprietà RenderTransform fa inclinare il controllo. Per l'elenco di codice completo, vedere Procedura: implementare una sbarra in un controllo.
In questa procedura dettagliata vengono eseguite le attività seguenti:
Creare un progetto di libreria di controlli personalizzati WPF.
Creare un assembly distinto per i metadati Design-Time.
Implementare il provider di strumenti decorativi visuali.
Verificare il controllo in fase di progettazione.
Al termine, si sarà in grado di creare uno strumento decorativo visuale per un controllo personalizzato.
![]() |
---|
Le finestre di dialogo e i comandi di menu visualizzati potrebbero non corrispondere a quelli descritti nella Guida in linea in quanto dipendono dall'edizione o dalle impostazioni attive. Per modificare le impostazioni, scegliere Importa/esporta impostazioni dal menu Strumenti. Per ulteriori informazioni, vedere Impostazioni di Visual Studio. |
Prerequisiti
Per completare questa procedura dettagliata, è necessario disporre dei seguenti componenti:
- Visual Studio 2008.
Creazione del controllo personalizzato
Il primo passaggio consiste nella creazione del progetto per il controllo personalizzato. Il controllo è un semplice pulsante con una piccola quantità di codice Design-Time che utilizza il metodo GetIsInDesignMode per implementare un comportamento in fase di progettazione.
Per creare il controllo personalizzato
In Visual Basic o Visual C# creare un nuovo progetto di libreria di controlli personalizzati WPF denominato SkewButtonLibrary.
Il codice per CustomControl1 verrà aperto nell'editor del codice.
In Esplora soluzioni modificare il nome del file di codice in SkewButton.cs o SkewButton.vb. Se viene visualizzata una finestra di messaggio in cui si richiede se eseguire un'operazione di ridenominazione per tutti i riferimenti del progetto, fare clic su Sì.
In Esplora soluzioni espandere la cartella Themes.
Fare doppio clic su Generic.xaml.
Generic1.xaml verrà aperto in WPF Designer.
In visualizzazione XAML sostituire tutte le occorrenze di "CustomControl1" con "SkewButton".
Aprire SkewButton.cs o SkewButton.vb nell'editor del codice.
Sostituire il codice generato automaticamente con il codice seguente. Il controllo personalizzato SkewButton eredita da Button e visualizza il testo "Design mode active" quando il pulsante viene visualizzato nella finestra di progettazione. Il controllo di GetIsInDesignMode e il seguente codice Design-Time sono facoltativi e sono illustrati solo per scopi dimostrativi.
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"; } } } }
Impostare il percorso di output del progetto su "bin\".
Compilare la soluzione.
Creazione dell'assembly di metadati Design-Time
Il codice Design-Time viene distribuito in speciali assembly di metadati. Per questa procedura dettagliata, lo strumento decorativo visuale personalizzato viene distribuito in un assembly denominato SkewButtonLibrary.VisualStudio.Design. Per ulteriori informazioni, vedere Archivio di metadati.
Per creare l'assembly di metadati Design-Time
In Visual Basic o Visual C# aggiungere un nuovo progetto di libreria di classi denominato SkewButtonLibrary.VisualStudio.Design alla soluzione.
Impostare il percorso di output del progetto su "..\SkewButtonLibrary\bin\". In questo modo l'assembly del controllo e l'assembly dei metadati verranno mantenuti nella stessa cartella, consentendo l'individuazione di metadati per le finestre di progettazione.
Aggiungere riferimenti agli assembly WPF riportati di seguito.
PresentationCore
PresentationFramework
WindowsBase
Aggiungere riferimenti agli assembly WPF Designer riportati di seguito.
Microsoft.Windows.Design
Microsoft.Windows.Design.Extensibility
Microsoft.Windows.Design.Interaction
Aggiungere un riferimento al progetto SkewButtonLibrary.
In Esplora soluzioni modificare il nome del file di codice Class1 in Metadata.cs o Metadata.vb. Se viene visualizzata una finestra di messaggio in cui si richiede se eseguire un'operazione di ridenominazione per tutti i riferimenti del progetto, fare clic su Sì.
Sostituire il codice generato automaticamente con il codice seguente. Con questo codice viene creato un oggetto AttributeTable che connette l'implementazione Design-Time personalizzata alla classe SkewButton.
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 ' 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() ' Add the adorner provider to the design-time metadata. builder.AddCustomAttributes(GetType(SkewButton), New FeatureAttribute(GetType(SkewButtonAdornerProvider))) 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 SkewButtonLibrary; using Microsoft.Windows.Design.Features; using Microsoft.Windows.Design.Metadata; using SkewButtonLibrary.VisualStudio.Design; namespace CiderPropertiesTester { // 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(); // Add the adorner provider to the design-time metadata. builder.AddCustomAttributes( typeof(SkewButton), new FeatureAttribute(typeof(SkewButtonAdornerProvider))); MetadataStore.AddAttributeTable(builder.CreateTable()); } } }
Salvare la soluzione.
Implementazione del provider di strumenti decorativi visuali
Il provider di strumenti decorativi visuali viene implementato in un tipo denominato SkewButtonAdornerProvider. Questo FeatureProvider di strumenti decorativi consente di impostare la proprietà RenderTransform del controllo in fase di progettazione.
Per implementare il provider di strumenti decorativi visuali
Aggiungere una nuova classe denominata SkewButtonAdornerProvider al progetto SkewButtonLibrary.VisualStudio.Design.
Nell'editor del codice per SkewButtonAdornerProvider sostituire il codice generato automaticamente con il codice seguente. Con questo codice viene implementato un PrimarySelectionAdornerProvider che fornisce uno strumento decorativo personalizzato.
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, 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 ' 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 ' Place the slider in the adorner panel. Dim placement As New AdornerPlacementCollection() AdornerPanel.SetHorizontalStretch(skewSlider, AdornerStretch.Stretch) AdornerPanel.SetVerticalStretch(skewSlider, AdornerStretch.None) ' Use layout space for the adorner panel. ' If render space were used, the slider would skew along with the button. panel.CoordinateSpace = AdornerCoordinateSpaces.Layout ' The adorner's width is relative to the content. ' The slider extends half the width of the control it adorns. placement.SizeRelativeToContentWidth(0.5, 0) ' Center the adorner within the control. placement.PositionRelativeToAdornerWidth(0.5, 0) ' The adorner's height is the same as the slider's. placement.SizeRelativeToAdornerDesiredHeight(1.0, 0) ' Position the adorner within the control it adorns. placement.PositionRelativeToAdornerHeight(1.0, 0) AdornerPanel.SetPlacements(skewSlider, placement) ' 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, 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.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 tf 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(Control.RenderTransformProperty) 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(Control.RenderTransformProperty).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, 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); // 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; // Place the slider in the adorner panel. AdornerPlacementCollection placement = new AdornerPlacementCollection(); AdornerPanel.SetHorizontalStretch(skewSlider, AdornerStretch.Stretch); AdornerPanel.SetVerticalStretch(skewSlider, AdornerStretch.None); // Use layout space for the adorner panel. // If render space were used, the slider would skew along with the button. panel.CoordinateSpace = AdornerCoordinateSpaces.Layout; // The adorner's width is relative to the content. // The slider extends half the width of the control it adorns. placement.SizeRelativeToContentWidth(0.5, 0); // Center the adorner within the control. placement.PositionRelativeToAdornerWidth(0.5, 0); // The adorner's height is the same as the slider's. placement.SizeRelativeToAdornerDesiredHeight(1.0, 0); // Position the adorner within the control it adorns. placement.PositionRelativeToAdornerHeight(1.0, 0); AdornerPanel.SetPlacements(skewSlider, placement); // 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, view); } // 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 tf 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[Control.RenderTransformProperty]; 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[ Control.RenderTransformProperty].ComputedValue as SkewTransform; return skewXform.AngleX; } } }
Compilare la soluzione.
Test dell'implementazione Design-Time
È possibile utilizzare il controllo SkewButton come qualsiasi altro controllo WPF. In WPF Designer viene gestita la creazione di tutti gli oggetti Design-Time.
Per eseguire il test dell'implementazione Design-Time
Aggiungere un nuovo progetto di applicazione WPF denominato DemoApplication alla soluzione.
Window1.xaml verrà aperto in WPF Designer.
Aggiungere un riferimento al progetto SkewButtonLibrary.
In visualizzazione XAML sostituire il codice XAML generato automaticamente con il seguente codice XAML. Con questo codice XAML viene aggiunto un riferimento allo spazio dei nomi SkewButtonLibrary e viene aggiunto il controllo personalizzato SkewButton. Il pulsante viene visualizzato in visualizzazione Progettazione con il testo "Design mode active", indicante che si trova in modalità progettazione. Se il pulsante non viene visualizzato, può essere necessario fare clic sulla barra informazioni nella parte superiore della finestra di progettazione per ricaricare la visualizzazione.
<Window x:Class="DemoApplication.Window1" 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>
<Window x:Class="DemoApplication.Window1" 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>
In visualizzazione Progettazione fare clic sul controllo SkewButton per selezionarlo.
Un controllo Slider viene visualizzato all'interno del controllo SkewButton. Se il dispositivo di scorrimento non viene visualizzato, provare di nuovo a compilare la soluzione.
Modificare il valore del controllo dispositivo di scorrimento.
Il controllo viene inclinato ma mano che si trascina il dispositivo di scorrimento. In visualizzazione XAML, la proprietà RenderTransform viene impostata sul valore specificato dallo strumento decorativo visuale.
Eseguire il progetto DemoApplication.
In fase di esecuzione il pulsante viene inclinato ad un angolo pari a quello impostato con lo strumento decorativo visuale.
Passaggi successivi
È possibile aggiungere altre funzionalità in fase di progettazione ai controlli personalizzati.
Aggiungere uno strumento decorativo personalizzato alla fase di progettazione del controllo. Per ulteriori informazioni, vedere Procedura dettagliata: creazione di uno strumento decorativo visuale in fase di progettazione.
Creare un provider di strumenti decorativi visuali per la modifica sul posto. Per ulteriori informazioni, vedere Procedura dettagliata: implementazione della modifica sul posto.
Creare un editor di colori personalizzato da utilizzare nella finestra Proprietà. Per ulteriori informazioni, vedere Procedura dettagliata: implementazione di un editor di colori.
Vedere anche
Attività
Procedura: implementare una sbarra in un controllo
Riferimenti
PrimarySelectionAdornerProvider