Write a picture button yourself (XAML)

Source: Internet
Author: User

Sometimes you need to use three pictures (normal, mouse, mouse down) as a button style, although this practice is not good, should be used in vector style, but sometimes it is necessary to do so.

Each time you modify the style of the button to achieve this, it is troublesome to generate a large section of the XAML code, not conducive to maintenance, pull out a custom picture button control, just pass through the path of three pictures to use, obviously a better way, the following shows how to write this control, VS2015 and Blend2015 are used together.

1. First, create a new WPF custom control library in VS, named Wpfcustomcontrollibrary, and the system will automatically generate a CustomControl1 class and generate a Themes folder. which contains a resource dictionary file generic.xaml. If you open the AssemblyInfo.cs file, you will see a code that contains the following

[Assembly:themeinfo (    Resourcedictionarylocation.none,///Topic specific resource dictionary location                             //(in the page, application, or any topic-specific resource dictionary                             // Used without a resource found)    resourcedictionarylocation.sourceassembly//General resource dictionary location                                      //(in the page, application, or any topic-specific resource dictionary                                      // Use if a resource is not found)]

This code indicates that the default style of the control is included in the Generic.xaml resource dictionary under the Themes folder, which is the difference between a WPF custom control library and a generic assembly.

2. Change the CustomControl1 class to ImageButton

At this point the initial code is as follows,

    public class Imagebutton:control    {        static ImageButton ()        {            Defaultstylekeyproperty.overridemetadata (typeof (ImageButton), New Frameworkpropertymetadata (typeof (ImageButton)) );        }    }
<ResourceDictionaryxmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local= "Clr-namespace:wpfcustomcontrollibrary">    <StyleTargetType="{x:type Local:imagebutton}">        <Setter Property= "Template">            <Setter.value>                <ControlTemplateTargetType="{x:type Local:imagebutton}">                    <BorderBackground="{TemplateBinding Background}"BorderBrush="{TemplateBinding BorderBrush}"borderthickness="{TemplateBinding BorderThickness}">                    </Border>                </ControlTemplate>            </Setter.value>        </Setter>    </Style></ResourceDictionary>

3. Change the base class of the ImageButton to button.

4. Add three dependency properties in ImageButton, as follows

        public static readonly DependencyProperty Normalimageproperty = dependencyproperty.registerattached ("No        Rmalimage ", typeof (ImageSource), typeof (ImageButton), new PropertyMetadata (null));            Public ImageSource Normalimage {get {return (ImageSource) GetValue (normalimageproperty);}        set {SetValue (Normalimageproperty, value);} } public static readonly DependencyProperty Mouseoverimageproperty = dependencyproperty.registerattached        ("Mouseoverimage", typeof (ImageSource), typeof (ImageButton), new PropertyMetadata (null));            Public ImageSource Mouseoverimage {get {return (ImageSource) GetValue (mouseoverimageproperty);}        set {SetValue (Mouseoverimageproperty, value);} } public static readonly DependencyProperty Pressedimageproperty = dependencyproperty.registerattached ("     Pressedimage ", typeof (ImageSource), typeof (ImageButton), new PropertyMetadata (null));   Public ImageSource Pressedimage {get {return (ImageSource) GetValue (pressedimageproperty);}        set {SetValue (Pressedimageproperty, value);} }

5. Create a new WPF Application project that references the custom control library, and in one page, add the ImageButton control. Select the ImageButton control, click [ImageButton] in the artboard navigation bar, select Edit Template in the popup menu-edit copy, enter Imagebuttonstyle in the popup dialog, select the document, click OK.

6. In the template editing state, right-click [Border] in the Document Outline panel, select Change Layout type-grid, and then clear the background of the Grid. Add three image controls to a grid and reset the layout. You can join from the assets panel and enter an image lookup in the search bar of the assets panel. Empty the width and height of the three image, and change the stretch property to none.

7. Change the source property of the three image from top to bottom to template bindings Normalimage,pressedimage and mouseoverimage, and modify the method to click the small square to the right of the Source property in the Properties panel. Select the template binding-normalimage. Change the visibility property of the pressedimage and mouseoverimage image to collapsed.

8. In the Status panel, click MouseOver, in the Document Outline panel, select the first image control, and in the Properties panel, change the visibility property to collapsed. Select the third image control that is mouseoverimage, and in the Properties panel, change the visibility property to visible.

In the status panel, click Pressed, in the Document Outline panel, select the first image control, and in the Properties panel, change the visibility property to collapsed. Select the second image control that is pressedimage, and in the Properties panel, change the visibility property to visible.

At this point the code for Imagebuttonstyle is as follows

<StyleTargetType="{x:type Local:imagebutton}">        <Setter Property= "Template">            <Setter.value>                <ControlTemplateTargetType="{x:type Local:imagebutton}">                    <Grid>                        <visualstatemanager.visualstategroups>                            <VisualStateGroupx:name= "CommonStates">                                <VisualStatex:name= "Normal"/>                                <VisualStatex:name= "MouseOver">                                    <Storyboard>                                        <ObjectanimationusingkeyframesStoryboard.TargetProperty= "(uielement.visibility)"Storyboard.TargetName= "image">                                            <DiscreteObjectKeyFrameKeyTime= "0"Value="{x:static visibility.collapsed}"/>                                        </Objectanimationusingkeyframes>                                        <ObjectanimationusingkeyframesStoryboard.TargetProperty= "(uielement.visibility)"Storyboard.TargetName= "Image1">                                            <DiscreteObjectKeyFrameKeyTime= "0"Value="{x:static visibility.visible}"/>                                        </Objectanimationusingkeyframes>                                    </Storyboard>                                </VisualState>                                <VisualStatex:name= "Pressed">                                    <Storyboard>                                        <ObjectanimationusingkeyframesStoryboard.TargetProperty= "(uielement.visibility)"Storyboard.TargetName= "image">                                            <DiscreteObjectKeyFrameKeyTime= "0"Value="{x:static visibility.collapsed}"/>                                        </Objectanimationusingkeyframes>                                        <ObjectanimationusingkeyframesStoryboard.TargetProperty= "(uielement.visibility)"Storyboard.TargetName= "Image2">                                            <DiscreteObjectKeyFrameKeyTime= "0"Value="{x:static visibility.visible}"/>                                        </Objectanimationusingkeyframes>                                    </Storyboard>                                </VisualState>                                <VisualStatex:name= "Disabled"/>                            </VisualStateGroup>                        </visualstatemanager.visualstategroups>                        <Imagex:name= "image"Source="{TemplateBinding Normalimage}"Stretch= "None"/>                        <Imagex:name= "Image2"Source="{TemplateBinding Pressedimage}"Stretch= "None"Visibility= "Collapsed"/>                        <Imagex:name= "Image1"Source="{TemplateBinding Mouseoverimage}"Stretch= "None"Visibility= "Collapsed"/>                    </Grid>                </ControlTemplate>            </Setter.value>        </Setter>    </Style>

9. Replace the controltemple portion of the ImageButton style in the Generic.xaml file in the Themes folder in the custom control library with the Controltemple section in this style. Note Modify TargetType to {x:type Local:imagebutton} ".

10. Now that the Picture button control is complete, on one page in the WPF Application project, add the ImageButton control (select item category) from the assets panel. Select the ImageButton control, as you can see in the Properties panel, under the Miscellaneous group, there are three properties for Normalimage,mouseoverimage and Pressedimage, and you can set a picture individually.

11. Set these three properties to three suitable images, the picture button can be used.

Write a picture button yourself (XAML)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.