Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
User controls inherit from the UserControl class which is a derive class of the Control class. We will be creating an EditableLabel control. It will exactly look at a lable but when the user double clicks it, it will transform into an editable textbox containing the current text of the label. You can then edit its contents and when the user presses enter, it will transform back into a label containing the edited text. Open Visual Studio and create a new project. Choose Windows Forms Control Library and name it EditableLabel. It looks just like a Windows Forms but it has no frame. This is because you are designing a user control. Any control you place inside it will be part of the user control. Click the canvas and change itsName property to EditableLabel and its AutoSize property to True. Drag a label to the canvas and change its Text property to Label and its Name property to labelDisplay. Resize the canvas so that it fits the label inside it.
Adding Properties
Since we are creating a user control, then it will only contain properties and events that the UserControlclass offers. To add a property to a user control, we simply need to add a property to the class of our user control. While in Design View, press F7 to go to the Code Editor. Inside the EditableLabel class, add the following property: [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public override string Text { get { return labelDisplay.Text; } set { labelDisplay.Text = value; } }
We added an event handler for the textbox's KeyDown event. When the user is finish editing the text, he or she can simply press the Enter or Return key. Here is the definition for the event handler of theKeyDown event: void editableTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { labelDisplay.Text = editableTextBox.Text; editableTextBox.Hide(); labelDisplay.Show(); } } First we checked if the key pressed by the user is the Enter key. Next, we set the Text of the currently hidden label into the new text entered by the user. We then hide the editableTextBox and reshow thelabelDisplay containing the updated text. Finally, when the label is resized depending on the length of text, we also need to resize the actual user control. Click labelDisplay in the Designer and in the Properties WIndow's Events section, find the Resize event and double click it. Use the following event handler for it. private void labelDisplay_Resize(object sender, EventArgs e) { this.Size = labelDisplay.Size; } The event handler simply sets the Size of the user control to the new Size of the labelDisplay.