Nibblestutotials.net tutorial-user control in the WPF Series

Source: Internet
Author: User

Nibblestutorials.net WPF tutorial-1 user control

User Control Part1-multiply! User Control Part 1-Increase

Project File Download

 

After I found the user control, my life had changed. Do not turn your eyes away from the word "control. They are some external Xmal andCodeObject. For flash designers, this means that you can use user controls by using video clips in flash. This section shows you how to create a simple user control without any post code to create multiple instances of a cute blue bird. Yes, this is a bird, not a fish.

 

    1. Create a new WPFProgram.
      1. OpenExpression blend 2 August Preview-Use expression blend 1.0.
      2. SelectFile> new project...OpenCreate a new projectDialog box.
      3. SelectWpfapplication (.exe).
      4. Name the projectBird, ClickOK.

      A new WPF project has been created, and the windows1.xaml file appears in the canvas.

    1. Create a user control
      1. ClickFile> Create a project...OpenAdd a new projectDialog box.
      2. ByTemplate installedSelectUser Control.
      3. Name the new user controlUserbird. XAML.

      For more information, see.

    1. Import illustration of bird (XAML format)
      1. InAttributePanelFile,Right-clickProject name and selectAdd existing project...
      2. Browse and findBird. XAMLFile. You can use the link at the top of the page to download this project. In my example, I put this file in c: \ nibbles \ bird. XAML.
      3. ClickOpenButton to import this XAML file.

    1. Open bird. XAML

      This XAML file contains an illustration of a bird. Illustration is a seriesPath(Vector graphics), so you can copy these paths from one file to another.

      1. InAttributeUnder the PanelFileMedium,Double-clickYou just importedBird. XAMLFile.

      Now you should see birds inPanel. For more information, see.

    1. Copy illustration by bird. XAML
      1. InInteractionIn the panelObject and timelineMedium,SelectBird object.
      2. PressCopy (CTRL + C)Copy the image to the clipboard.

    1. Copy the illustration to userbird. XAML.
      1. SelectUserbird. XAMLTag, located above the window (see figure ).
      2. PressPaste (CTRL + V)Paste the illustration into the new XAML.

      You should get the effect shown in the figure.

    1. Adjust the widget size
      1. InInteractionPanelObject and timelineMedium,Select User ControlObject. See the highlighted area.
      2. In the layout of the property panel, adjust the size of the user controlWidth = 330,Hight = 300. See the highlighted area.

      Yes! Your User Control is ready...

    1. Generate an application

      To access your new user control, you should first generate an application. The generated action causes the userbird controlResource Library.

      1. SelectProject> Generate a projectTo generate a project.

    1. Select a new user control
      1. SelectWindows1.xamlLabel (see the highlighted area ).
      2. Click the highlighted arrow to openResource LibraryPanel.
      3. ByResource LibraryPanel, clickCustom ControlsLabel.
      4. Then clickUserbirdAnd select it.

    1. Draw birds on the canvas

      Now you only need to draw it!

      1. Click and drag the bird to the canvas to create a new instance of the bird.
      2. Or right-click the userbird button (highlighted on the way ).

 

User Control Part1-multiply! User Controls Part 2-diversity

Now, let's add some color to these items. In the first part of this tutorial, you learned how to create a user control and use multiple instances of this control in your WPF project.

This part of the tutorial shows you how to expose the attributes of the user control (such as the color attribute). This attribute allows you to change the color of each bird separately. You can only use the blend design interface! Download the following project ZIP file and start.

This part is an example file.

  1. Download and open the project
    1. Download the project file to your computer and use the above link.
    2. OpenExpression blend 2 August Preview-Use expression blend 1.0..
    3. SelectFile> open project...OpenOpen a projectDialog box.
    4. Browse and find the folder of the project you just downloaded. Double-clickBird. slnFile Open project.

  2. Open User Control
    1. InAttributePanelFile, Double-clickUserbird. XAMLOpen it.

    If you do not know how to create a user control, see the first part of this tutorial (above ).

    This part of the sample file is different from the first part. Note that there are some elements in the element tree that use color1, color2, color3... The path object named by color10. We will use code to change the color of these objects, which is why they need to be properly named. Highlighted objectsColor1.

  3. Open a project in Visual Studio

    We will useVisual Studio 2005EditC #Code. You can use other editors you like. We chooseVSThe reason is that it correspondsExpression BlendWell integrated.

    You need to installVisual Studio 2005.

    1. InProjectPanelFileInProject nameUpperRight-click. In the context menu, selectEdit in Visual Studio(SEE ).

    Visual StudioWill open and share the same project with blend.

  4. Open the post code of userbird

    When we createUser ControlWill automatically generatePost CodeFile. In this project, the post code isUserbird. XAMLIntegrated C # files.

    1. InSolutionPanel, double-clickUserbird. XAML. CSFile. See.

    C # some references are at the beginning of the Code, and there is also a constructor. Now we need to add some code to create a new property for this user control and expose it to the blend user interface.

  5. Add get () and set ()

    We name the color attributeBirdcolorproperty. Although we change the color to update the user interface, we need to create a method to handle this when the property value changes.Get ()AndSet ().

Public StringBirdcolor

{

Get

{

Return(String)Base. Getvalue (birdcolorproperty );

}

Set

{

Base. Setvalue (birdcolorproperty. value );

This. Initbird ();

}

}

 

For more information, see.

    1. Declare dependency attributes

      We willBirdcolorpropertyUse the following code to declare a Dependency Property:

Public Static Readonly DependencypropertyBirdcolorproperty

=Dependencyproperty. Register ("Birdcolor",

Typeof(String),Typeof(Userbird),

New Propertymetadata(

New Propertychangedcallback(Handlebirdcolorchanged )));

 

Okay, so long line. Let's explain each part:

Public Static Readonly DependencypropertyBirdcolorproperty

=Dependencyproperty. Register ();

 

This is the dependency attribute defined in C #. RegisterBirdcolorpropertyAttribute method. Then we use the following parameters:

Birdcolor: Name of the method we just created.

Typeof (string): Attribute type.

Typeof (userbird): Our own type. In this example, it is a partially classified userbird.

New propertymetadata (New propertychangedcallback (handlebirdcolorchanged )): Defines the method called when the attribute changes. This method will be defined in the next step.

    1. Add handlebirdcolorchanged ()

      This method is called every time the attribute is changed. This method only calls another method to update the color of all paths.

Private Static VoidHandlebirdcolorchanged

(DependencyobjectSource,DependencypropertychangedeventargsE)

{

((Userbird) Source). initbird ();

}

Initbird ()It will be defined in the next step.

    1. How to add and update colors

      The color of this code will be updated:

Public VoidInitbird ()

{

Try

{

For(IntI = 1; I <= 10; I ++)

{

System. Windows. shapes.PathE = (system. Windows. shapes.Path) Layoutroot. findname ("Color"+ I );

E. Fill =New Solidcolorbrush((Color)Colorconverter. Convertfromstring (This. Birdcolor ));

}

}

Catch(SystemexceptionErr)

{

For(IntI = 1; I <= 10; I ++)

{

System. Windows. shapes.PathE = (system. Windows. shapes.Path) Layoutroot. findname ("Color"+ I );

E. Fill =New Solidcolorbrush((Color)Colorconverter. Convertfromstring ("# Ff666666"));

}

}

}

This code Looks longer than it actually looks because it has duplicates. We need to placeTry ()... Catch ()Block to prevent invalid color. Try and the code in catch perform the same functions:

For Loop: Defines the number of objects to be updated named color [N. In this example, there are 10 objects.

System. Windows. shapes. Path E =

(System. Windows. shapes. Path) layoutroot. findname ("color" + I );

Find each object defined as a path.

E. Fill = new solidcolorbrush (color) colorconverter. convertfromstring (this. birdcolor ));

Change the color of each shape based on the value of the previously defined dependency attribute.

Or...

E. Fill = new solidcolorbrush (color) colorconverter. convertfromstring (# ff666666 ));

If the value in the Dependency Property is invalid, change the color to the default gray color.

Okay! Let's see how these work in blend.

  1. Generate a project

    It is a good practice to build a project before opening the user control in blend. You can generate a project in Visual Studio or in expression blend.

    1. SaveUserbird. XAML. CS.
    2. BackExpression Blend.
    3. SelectProject> Generate a projectTo generate this project.

    You can seeGenerated successfully).

  2. Select a new user control
    1. SelectWindow1.xamlTab (highlighted ).
    2. Click the highlighted arrow () to openResource LibraryPanel.
    3. ByResource LibraryPanel, clickCustom ControlsTab.
    4. ClickUserbirdAnd select it.

  3. Add a birdcontrol

    Now you only need to start painting.

    1. Click and drag to draw a new instance of the birdCanvas.
    2. Alternatively, double-click the userbird button (highlighted in the figure ).

  4. Change color
    1. Select any userbird instance in the canvas.
    2. Find the Dependency Property birdcolor in miscellaneous on the property panel.
    3. Enter a valid color such as green or # ff450099. You should see that the whole bird has changed to a new color.
    4. Add several instances and give each bird a different color...

 

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.