. Net CF 1.0->. Net CF 2.0->. Net cf3.5
With the upgrade of the CF version, we are constantly using the new features provided by CF. Have you ever thought about how to improveCodeQuality? Not only does it make the Code look clearer?
With the launch of C #3.0, I believe that generics have become a widely used term. In future projects, we will not try to use it to create controls.
Previously, we added a control to form using the following method:
1 Button clickbutton = New Button ();
2 Clickbutton. Name = " Button " ;
3 Clickbutton. Text = " Click me " ;
4 Clickbutton. Location = New Point ( 100 , 200 );
5 Clickbutton. Font = This . Font;
6 This . Controls. Add (clickbutton );
We use the model to improve the following:
1 Public Form1 ()
2 {
3 Initializecomponent ();
4
5 // Create button and add it to the form's controls collection
6 Button clickbutton = This . Addcontrol < Button > (C => New Button ()
7 {
8 Name = " Button " ,
9 Text = " Click me " ,
10 Location = New Point ( 100 , 200 ),
11 Font = C. Font
12 });
13 // Hook up into the Click Event
14 Clickbutton. Click + = New Eventhandler (clickbutton_click );
15 // Create label
16 This . Addcontrol < Label > (C => New Label ()
17 {
18 Name = " Labelhello " ,
19 Location = New Point ( 100 , 240 )
20 });
21 }
22
23 Void Clickbutton_click ( Object Sender, eventargs E)
24 {
25 // Assign the value to the text property of the label
26 This . Getcontrol < Label > ( " Labelhello " ). Text = " Hello world. " ;
27 }
1 Public Static Class Controlextension
2 {
3 Public Static T addcontrol < T > ( This Control parent, func < Control, T > Build)
4 {
5 T control = Build (parent );
6 Parent. Controls. Add (Control As Control );
7 Return Control;
8 }
9
10 Public Static Control getcontrol ( This Control parent, String Name)
11 {
12 Return Parent. Controls. oftype < Control > (). Singleordefault (C => C. Name = Name );
13 }
14
15 Public Static T getcontrol < T > ( This Control parent, String Name) Where T: Control
16 {
17 Return Parent. Controls. oftype < Control > (). Singleordefault (C => C. Name = Name) As T;
18 }
19 }
In this way, the code looks clearer. Although some additional work is done, it makes our work more effective.
Advantage: the code is clearer and can be used to dynamically add controls.
Disadvantage: the code and design are not compatible, which is not conducive to UI debugging. It is not applicable to non-dynamic addition of controls. After all, it is very resource-consuming to dynamically create many controls through. Net CF in the WM system.
This articleArticleReference: Alex yakhnin's 《Generic control creation."
The code in this article must be modified in WM. In the controlextension class, the parent. Controls collection object does not support directly using the name to find the control. Therefore, we need to make some small adjustments.
Running Environment: vs2008+ Wm6.0 +. Net cf3.5
Author: appleseeker (Feng)
Date: 2009-01-23
Article introduction:Mobile Development Index stickers