Netframwork 2.0 (phần 14) pot

50 251 0
Netframwork 2.0 (phần 14) pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lesson 1: Creating Composite Controls 625 Lesson 1: Creating Composite Controls Composite controls are the simplest form of user-created controls. The composite con- trol designer includes a graphical interface similar to a form that allows you to add preexisting controls and components, which are then bound together in a single func- tional unit. In this lesson, you will learn how to create a composite control as well as some general methods for control development. After this lesson, you will be able to: ■ Develop a user (composite) Windows Forms control. ■ Create properties, methods, and events for Windows Forms controls. ■ Expose properties of constituent controls. ■ Configure a control to be invisible at run time. ■ Configure a control to have a transparent background. ■ Provide a Toolbox Bitmap for a control. Estimated lesson time: 45 minutes Introduction to Composite Controls Composite controls (also known as user controls) are just as they sound: controls that are made up of other controls. Composite controls inherit from the UserControl class. The UserControl class provides a base level of functionality that you can build on by adding other controls as well as additional properties, methods, and events. The User- Control class has its own designer that allows you to use the Visual Studio Integrated Design Environment to drag additional controls from the Toolbox to the design sur- face and configure them. The UserControl designer is shown in Figure 14-1. Figure 14-1 The UserControl designer 626 Chapter 14 Creating Windows Forms Controls � To add a composite control to a solution at design time 1. From the Project menu, choose Add User Control. The Add New Item dialog box opens. 2. Name your control and click Add. The new control is added to the project and opened for editing in the designer. You can create a composite control in code by inheriting from the UserControl class, as shown here: ' VB Public Class myControl Inherits UserControl ' Add implementation here End Class // C# public class myControl : UserControl { // Add implementation here } The subordinate controls that make up the composite control are called constituent controls. You can add constituent controls to your composite control in the same way that you would add a control to a form—by dragging it onto the design surface from the Toolbox. You can configure these constituent controls in the same way that you would configure them in a form—you can set properties, alter the visual appearance, and create methods that handle control events. When the composite control is built, the functionality that you have coded will be built into the composite control. Adding Methods, Properties, and Events to Controls In addition to adding constituent controls, you can also add additional functionality to your control in the form of methods, properties, and events. NOTE Classes, controls, and composite controls The information in this section can be applied to classes and controls of all types, not just to com- posite controls. Adding Methods to a Control You can add a method to a control in the same way that you would add a method to a form or to any other class. Within the bounds of the class declaration in the Code window, add the method declaration and the method body. For a method that does not return a value, create a Sub (Visual Basic) or a void (C#) method, as shown here: Lesson 1: Creating Composite Controls 627 ' VB Public Sub DisplayString(ByVal aString As String) Msgbox(aString) End Sub // C# public void DisplayString(string aString) { MessageBox.Show(aString); } For methods that return a value, create a Function (Visual Basic) or specify the return type (C#), as shown in this example: ' VB Public Function DisplayString(ByVal aString As String, ByVal bString As String) As String Return aString & bString End Function // C# public string DisplayString(string aString, string bString) { return aString + bString; } Adding Properties to a Control Adding a property is similar to adding a method. You create a property definition and then implement the functionality required to return and set the value represented by the property. Usually, the underlying value for the property is stored in a private member variable. In Visual Basic, you use the Property keyword to create a property. In C#, you simply implement the getter and setter for the property. The following example demonstrates how to implement a property, including a member variable to contain the value. ' VB Private mUnitsOnHand Public Property UnitsOnHand() As Integer Get Return mUnitsOnHand End Get Set(ByVal value As Integer) mUnitsOnHand = value End Set End Property // C# private int mUnitsOnHand; public int UnitsOnHand { 628 Chapter 14 Creating Windows Forms Controls get { return mUnitsOnHand; } set { mUnitsOnHand = value; } } You can create a read-only property by using the ReadOnly keyword in Visual Basic or by simply omitting the setter in C#. An example is shown here: ' VB Private mUnitsOnHand Public ReadOnly Property UnitsOnHand() As Integer Get Return mUnitsOnHand End Get End Property // C# private int mUnitsOnHand; public int UnitsOnHand { get { return mUnitsOnHand; } } If creating a read-only property, you must set the member variable that represents the property’s value in code. Adding Events to a Control You can add events to a control that can be raised to notify the rest of the application that something interesting has happened. Once an event has been added to a class or control, it can be raised in code to send a notifica- tion to the rest of the application. In Visual Basic, you can create an event by using the Event keyword and specifying the name and signature of the event, as shown here: ' VB Public Event Bang(ByVal decibels As Integer) On the other hand, C# requires an explicit delegate to be present to specify the signa- ture before the event keyword can be used to create a new event. The following exam- ple demonstrates how to create an event in C#: // C# public delegate void Sound(int decibels); public event Sound Bang; Note that you specify the delegate itself, not an instance of the delegate. Lesson 1: Creating Composite Controls 629 You can raise an event in code by using the RaiseEvent keyword in Visual Basic or by simply calling the Event like you would a method in C#. An example is shown here: ' VB RaiseEvent Bang(100) // C# this.Bang(100); Exposing the Properties of Constituent Controls When constituent controls are added to a composite control, they are given an access level of Friend in by-default Visual Basic and private in C#. In both cases, the constit- uent controls will be inaccessible to classes in other assemblies. If you want to allow other assemblies to configure parts of the constituent controls, you must expose the properties of the constituent controls by wrapping them in a property declaration and then writing code in the composite control’s property to get and set the value of the constituent control’s property. For example, suppose you wanted to expose the Back- Color property of a constituent Button. You might create a property in the composite control called ButtonBackColor, in which you return the BackColor property of the con- stituent Button in the getter and set the constituent BackColor property of the Button in the setter. An example of how you might implement this is shown here: ' VB Public Property ButtonBackColor() As System.Drawing.Color Get Return Button1.BackColor End Get Set(ByVal value As System.Drawing.Color) Button1.BackColor = value End Set End Property // C# public System.Drawing.Color ButtonBackColor { get { return Button1.BackColor; } set { Button1.BackColor = value; } } Configuring a Control to Be Invisible at Run Time At times, you might want your control to be invisible at run time. You can create an invisible control by setting the Visible property to False. Controls that are invisible can- not interact with the user through the user interface, but they can still interact with 630 Chapter 14 Creating Windows Forms Controls application and other controls. The following example demonstrates how to set the Visible property to False: ' VB myUserControl.Visible = False // C myUserControl.Visible = false; Note that the Visible property can be set only at run time. To ensure that a control is invisible at startup, set the Visible property to False in the control’s Load event handler. Configuring a Control to Have a Transparent Background When configuring your control to have a transparent background, there are two types of transparencies to consider. A control can be transparent so that the visible appear- ance of the form underneath the control is seen through the background of the con- trol. A control can also appear as a transparent window through the form, displaying whatever is on the desktop beneath the form. To create a control with a transparent background color, all you need to do is set the BackColor property to Color.Transparent. Whatever is displayed on the form beneath the control will show through the background of the control. You can set the Back- Color to Transparent in the Properties window at design time, or you can set the Back- Color in code, as shown here: ' VB Me.BackColor = Color.Transparent // C# this.BackColor = Color.Transparent; Creating a transparent control that acts as a window through the form is a little more complex. Each form has a property called TransparencyKey, which represents a color that will appear as transparent when represented on the form. By setting the Back- Color property of the control to the same color as the form’s TransparencyKey property, you can create a window of transparency through the form. You can set the form’s TransparencyKey property and the control’s BackColor property in the Designer at design time or in code, as shown here: ' VB Form1.TransparencyKey = Color.Red myUserControl.BackColor = Color.Red Lesson 1: Creating Composite Controls 631 // C# Form1.TransparencyKey = Color.Red; myUserControl.BackColor = Color.Red; Providing a Toolbox Bitmap for Your Control After a control has been built, it automatically appears in the Toolbox if you are using it in the same solution that contains the control, or it can be added to the Toolbox if it was created in a different project. When the control is added to the Toolbox, it appears in the Toolbox as the name of the control next to an icon. If no icon is speci- fied, a generic icon is supplied. You can specify the icon that is displayed next to the name of your control by using the ToolboxBitmapAttribute. You can attach instances of the ToolboxBitmapAttribute class to your control declaration and use it to specify a 16 by 16 pixel bitmap that will be used to represent your control in the Toolbox. You can specify the Toolbox bitmap in three different ways. The most straightforward is to simply specify the path to the bitmap that you want to use. Here is an example of how to do this: ' VB <ToolBoxBitmap("C:\myToolboxBitmap.bmp")> Class myControl Inherits UserControl ‘ Implementation omitted End Class // C# [ToolBoxBitmap(@"C:\myToolboxBitmap.bmp")] class myControl : UserControl {} You can also use the ToolboxBitmap from an existing type. For example, you could specify the same ToolboxBitmap as is used by the Button control with the following code. ' VB <ToolBoxBitmap(GetType(System.Windows.Forms.Button))> Class myControl Inherits UserControl ' Implementation omitted End Class // C# [ToolBoxBitmap(GetType(System.Windows.Forms.Button))] class myControl : UserControl {} 632 Chapter 14 Creating Windows Forms Controls Finally, you can specify an assembly by specifying a type defined in that assembly and then load an icon resource that is specified by a string name, as shown: ' VB <ToolBoxBitmap(GetType(myControl), "myControl.bmp")> Class myControl Inherits UserControl ' Implementation omitted End Class // C# [ToolBoxBitmap(GetType(myControl), "myControl.bmp")] class myControl : UserControl {} Quick Check 1. Briefly explain what a composite control is. 2. How can you expose properties of constituent controls to developers? Quick Check Answers 1. A composite control, also called a user control, is a control that is made up of other preexisting controls (called constituent controls) bound together in a single interface. Composite controls can incorporate custom function- ality to enable the constituent controls to work together. 2. You expose properties of constituent controls to developers by wrapping them in user control properties. Lab: Create a Composite Control In this lab, you will create a simple composite control that acts as a digital clock. You will add a Label control to your composite control that displays the correct time and a Timer component that updates the Label every second. Finally, you will expose the Enabled property of the Timer control through your composite control to allow users to enable and disable the clock. � Exercise 1: Create a Digital Clock 1. Create a new Windows Forms application in Visual Studio. 2. From the Project menu, choose Add User Control and click Add in the Add New Item dialog box. A new user control is added to your project and opens in the Designer. Lesson 1: Creating Composite Controls 633 3. From the Toolbox, drag a Label control onto the user control. Resize the user control so that it is approximately the size of the Label control. 4. From the Toolbox, drag a Timer component onto the user control. 5. In the Properties window, set the Interval property for the Timer component to 1000 and the Enabled property to True. 6. Double-click the Timer component to open the Code window to the default event handler for the Timer.Tick event and add the following line of code: ' VB Label1.Text = Now.ToLongTimeString // C# label1.Text = DateTime.Now.ToLongTimeString(); 7. In the Code window, add the following Property declaration: ' VB Public Property TimeEnabled() As Boolean Get Return Timer1.Enabled End Get Set(ByVal value As Boolean) Timer1.Enabled = value End Set End Property // C# public bool TimeEnabled { get { return timer1.Enabled; } set { timer1.Enabled = value; } } 8. From the File menu, choose Save All to save your solution. 9. From the Build menu, build your solution. 10. In the Designer, choose the tab for Form1. From the Toolbox, drag a UserControl1 onto the form. An instance of your user control is added to the form and begins keeping time every second. Note that you can pause it by setting the TimeEnabled property to False in the Properties window. 11. Press F5 to build and run your application. Note that the user control functions the same way at run time as it does in the Designer. 634 Chapter 14 Creating Windows Forms Controls Lesson Summary ■ Composite controls, also called user controls, consist of preexisting Windows Forms controls and components bound together by common functionality in a common user interface. Controls that are contained in a composite control are called constituent controls. You can add additional methods, properties, and events to a composite control to create custom functionality. ■ Properties of constituent controls are not generally accessible to developers. You can expose properties of constituent controls by wrapping them in new proper- ties of the composite control. ■ You can configure a control to be invisible at run time by setting the Visible prop- erty to False. You can create a control with a transparent background by setting the BackColor property to Color.Transparent. You can create a window through the control and its owning form by setting the control’s BackColor property to the same color as the Form’s TransparencyKey property. ■ You can provide a Toolbox bitmap for a control by configuring the ToolboxBitmap attribute. Lesson Review The following questions are intended to reinforce key information presented in this lesson. The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE Answers Answers to these questions and explanations of why each choice is right or wrong are located in the “Answers” section at the end of the book. 1. Which of the following are characteristics of a composite control? (Choose all that apply.) A. Composite controls are made up of preexisting Windows Forms controls. B. Composite controls can have custom functionality in the form of new methods, properties, or events. C. Composite controls must provide their own rendering code. D. Composite controls automatically expose the properties of their constitu- ent controls as their own properties. . of the upper left hand 6 42 Chapter 14 Creating Windows Forms Controls // corner of the rendered string. g.DrawString(myString, myFont, SystemBrushes.Highlight, 20 , 20 ); g.Dispose(); Rendering. SolidBrush(Color.PapayaWhip) Dim g As Graphics = Me.CreateGraphics() Dim myRectangle As New Rectangle (0, 0, 10, 30) g.FillEllipse(myBrush, myRectangle) g.Dispose() myBrush.Dispose() // C# SolidBrush myBrush. SolidBrush(Color.PapayaWhip); Graphics g = this.CreateGraphics(); Rectangle myRectangle = new Rectangle (0, 0, 10, 30) ; g.FillEllipse(myBrush, myRectangle); g.Dispose(); myBrush.Dispose(); Note that you should

Ngày đăng: 07/07/2014, 05:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan