Export (0) Print
Expand All

Walkthrough: Creating a Design-time Adorner

This walkthrough shows how to create a design-time adorner for a Windows Presentation Foundation (WPF) custom control. You can use this adorner in the Windows Presentation Foundation (WPF) Designer for Visual Studio to set the value of the Opacity property on a custom button control. For this walkthrough, the control is a simple button and the adorner is a slider that allows you to change the opacity of the button. For a complete code listing, see How to: Create a Design-time Adorner.

In this walkthrough, you perform the following tasks:

  • Create a WPF custom control library project.

  • Create a separate assembly for design-time metadata.

  • Implement the adorner provider.

  • Test the control at design time.

When you are finished, you will know how create an adorner provider for a custom control.

NoteNote:

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.

You need the following components to complete this walkthrough:

  • Visual Studio 2008.

The first step is to create the project for the custom control. The control is a simple button with small amount of design-time code, which uses the GetIsInDesignMode method to implement a design-time behavior.

To create the custom control

  1. Create a new WPF Custom Control Library project in Visual Basic or Visual C# named CustomControlLibrary.

    The code for CustomControl1 opens in the Code Editor.

  2. In Solution Explorer, change the name of the code file to ButtonWithDesignTime.cs or ButtonWithDesignTime.vb. If a message box appears that asks if you want to perform a rename for all references in this project, click Yes.

  3. In Solution Explorer, expand the Themes folder.

  4. Double-click Generic.xaml.

    Generic.xaml opens in the WPF Designer.

  5. In XAML view, replace all occurrences of "CustomControl1" with "ButtonWithDesignTime".

  6. Open ButtonWithDesignTime.cs or ButtonWithDesignTime.vb in the Code Editor.

  7. Replace the automatically generated code with the following code. The ButtonWithDesignTime custom control inherits from Button and displays the text "Design mode active" when the button appears in the designer. The GetIsInDesignMode check and the following design-time code are optional and shown only for demonstration.

    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";
                }
            }
        }
    }
    
  8. Set the project's output path to "bin\".

  9. Build the solution.

Design-time code is deployed in special metadata assemblies. For more information, see How to: Use the Metadata Store. For this walkthrough, the custom adorner is supported by Visual Studio only and is deployed in an assembly named CustomControlLibrary.VisualStudio.Design.

To create the design-time metadata assembly

  1. Add a new Class Library project in Visual Basic or Visual C# named CustomControlLibrary.VisualStudio.Design to the solution.

  2. Set the project's output path to "..\CustomControlLibrary\bin\". This keeps the control's assembly and the metadata assembly in the same folder, which enables metadata discovery for designers.

  3. Add references to the following WPF assemblies.

    • PresentationCore

    • PresentationFramework

    • WindowsBase

  4. Add references to the following WPF Designer assemblies.

    • Microsoft.Windows.Design

    • Microsoft.Windows.Design.Extensibility

    • Microsoft.Windows.Design.Interaction

  5. Add a reference to the CustomControlLibrary project.

  6. In Solution Explorer, change the name of the Class1 code file to Metadata.cs or Metadata.vb.

  7. Replace the automatically generated code with the following code. This code creates an AttributeTable which attaches the custom design-time implementation to the ButtonWithDesignTime 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 CustomControlLibrary;
    using Microsoft.Windows.Design.Features;
    using Microsoft.Windows.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 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(ButtonWithDesignTime), 
                    new FeatureAttribute(typeof(OpacitySliderAdornerProvider)));
    
                MetadataStore.AddAttributeTable(builder.CreateTable());
            }
        }
    }
    
  8. Save the solution.

The adorner provider is implemented in a type named OpacitySliderAdornerProvider. This adorner enables the user to set the control's Opacity property at design time.

To implement the adorner provider

  1. Add a new class named OpacitySliderAdornerProvider to the CustomControlLibrary.VisualStudio.Design project.

  2. In the Code Editor for OpacitySliderAdornerProvider, replace the automatically generated code with the following code. This code implements a PrimarySelectionAdornerProvider which provides an adorner based on a Slider control.

    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, 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.
                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;
    
                AdornerPanel.SetHorizontalStretch(opacitySlider, AdornerStretch.Stretch);
                AdornerPanel.SetVerticalStretch(opacitySlider, AdornerStretch.None);
    
                AdornerPlacementCollection placement = new AdornerPlacementCollection();
    
                // The adorner's width is relative to the content. 
                // The slider extends the full width of the control it adorns.
                placement.SizeRelativeToContentWidth(1.0, 0);
    
                // The adorner's height is the same as the slider's.
                placement.SizeRelativeToAdornerDesiredHeight(1.0, 0);
    
                // Position the adorner above the control it adorns.
                placement.PositionRelativeToAdornerHeight(-1.0, 0);
    
                // Position the adorner up 5 pixels. This demonstrates  
                // that these placement calls are additive. These two calls 
                // are equivalent to the following single call: 
                // PositionRelativeToAdornerHeight(-1.0, -5).
                placement.PositionRelativeToAdornerHeight(0, -5);
    
                AdornerPanel.SetPlacements(opacitySlider, placement);
    
                // 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, 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.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[Control.BackgroundProperty];
                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[Brush.OpacityProperty].SetValue(newOpacityValue);
            }
    
            // This utility method gets the adorned control's 
            // Background brush by using the ModelItem. 
            private double GetCurrentOpacity()
            {
                Brush backgroundBrushComputedValue = 
                    (Brush)adornedControlModel.Properties[Control.BackgroundProperty].ComputedValue;
    
                return backgroundBrushComputedValue.Opacity;
            }
        }
    }
    
  3. Build the solution.

You can use the ButtonWithDesignTime control as you would use any other WPF control. The WPF Designer handles the creation of all design-time objects.

To test the design-time implementation

  1. Add a new WPF Application project in Visual Basic or Visual C# named DemoApplication to the solution.

    Window1.xaml opens in the WPF Designer.

  2. Add a reference to the CustomControlLibrary project.

  3. In XAML view, replace the automatically generated XAML with the following XAML. This XAML adds a reference to the CustomControlLibrary namespace and adds the ButtonWithDesignTime custom control. The button appears in Design view with the text "Design mode active", indicating that it is in design mode. If the button does not appear, you might have to click the Information bar at the top of the designer to reload the view.

    <Window x:Class="DemoApplication.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://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>
    
    <Window x:Class="DemoApplication.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://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. In the Design view, click the ButtonWithDesignTime control to select it.

    A Slider control appears above the ButtonWithDesignTime control.

  5. Use the slider control adorner to change the opacity of the button.

    In XAML view, the Opacity property is set to the value specified by the Slider control.

  6. Run the DemoApplication project.

    At run time, the button has the opacity you set with the adorner.

You can add more custom design-time features to your custom controls.

Community Additions

ADD
Show:
© 2015 Microsoft