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.
- Create a new WPFProgram.
- OpenExpression blend 2 August Preview-Use expression blend 1.0.
- SelectFile> new project...OpenCreate a new projectDialog box.
- SelectWpfapplication (.exe).
- Name the projectBird, ClickOK.
A new WPF project has been created, and the windows1.xaml file appears in the canvas.
- Create a user control
- ClickFile> Create a project...OpenAdd a new projectDialog box.
- ByTemplate installedSelectUser Control.
- Name the new user controlUserbird. XAML.
For more information, see.
- Import illustration of bird (XAML format)
- InAttributePanelFile,Right-clickProject name and selectAdd existing project...
- 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.
- ClickOpenButton to import this XAML file.
- 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.
- InAttributeUnder the PanelFileMedium,Double-clickYou just importedBird. XAMLFile.
Now you should see birds inPanel. For more information, see.
- Copy illustration by bird. XAML
- InInteractionIn the panelObject and timelineMedium,SelectBird object.
- PressCopy (CTRL + C)Copy the image to the clipboard.
- Copy the illustration to userbird. XAML.
- SelectUserbird. XAMLTag, located above the window (see figure ).
- PressPaste (CTRL + V)Paste the illustration into the new XAML.
You should get the effect shown in the figure.
- Adjust the widget size
- InInteractionPanelObject and timelineMedium,Select User ControlObject. See the highlighted area.
- 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...
- Generate an application
To access your new user control, you should first generate an application. The generated action causes the userbird controlResource Library.
- SelectProject> Generate a projectTo generate a project.
- Select a new user control
- SelectWindows1.xamlLabel (see the highlighted area ).
- Click the highlighted arrow to openResource LibraryPanel.
- ByResource LibraryPanel, clickCustom ControlsLabel.
- Then clickUserbirdAnd select it.
- Draw birds on the canvas
Now you only need to draw it!
- Click and drag the bird to the canvas to create a new instance of the bird.
- 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.
- Download and open the project
- Download the project file to your computer and use the above link.
- OpenExpression blend 2 August Preview-Use expression blend 1.0..
- SelectFile> open project...OpenOpen a projectDialog box.
- Browse and find the folder of the project you just downloaded. Double-clickBird. slnFile Open project.
-
- Open User Control
- 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.
- 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.
- InProjectPanelFileInProject nameUpperRight-click. In the context menu, selectEdit in Visual Studio(SEE ).
Visual StudioWill open and share the same project with blend.
-
- Open the post code of userbird
When we createUser ControlWill automatically generatePost CodeFile. In this project, the post code isUserbird. XAMLIntegrated C # files.
- 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.
- 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.
- 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.
- 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.
- 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.
-
- 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.
- SaveUserbird. XAML. CS.
- BackExpression Blend.
- SelectProject> Generate a projectTo generate this project.
You can seeGenerated successfully).
-
- Select a new user control
- SelectWindow1.xamlTab (highlighted ).
- Click the highlighted arrow () to openResource LibraryPanel.
- ByResource LibraryPanel, clickCustom ControlsTab.
- ClickUserbirdAnd select it.
-
- Add a birdcontrol
Now you only need to start painting.
- Click and drag to draw a new instance of the birdCanvas.
- Alternatively, double-click the userbird button (highlighted in the figure ).
- Change color
- Select any userbird instance in the canvas.
- Find the Dependency Property birdcolor in miscellaneous on the property panel.
- Enter a valid color such as green or # ff450099. You should see that the whole bird has changed to a new color.
- Add several instances and give each bird a different color...