创建您自己的标签控件非常简单,您只需从 Control 开始并重写 OnPaint() 即可。去byte就是把它变成一个也有聚焦行为的控件。并允许用户编辑文本。完成后,您将重新发明 TextBox 控件。这比看起来要难得多。
首先集中注意力,这是最棘手的问题。用户不太可能想要频繁地聚焦控件。也许是某种秘密握手,例如双击。当您检测到一个时,您可以创建一个 TextBox 控件并将其放在标签前面。并在失去焦点时将其丢弃,更新标签的 Text 属性。或者一个显示小型编辑对话框的简单上下文菜单。
使用双击编辑方法的示例:
using System;
using System.Windows.Forms;
class MyLabel : Label {
private TextBox mEditor;
protected override void OnDoubleClick(EventArgs e) {
if (mEditor == null) {
mEditor = new TextBox();
mEditor.Location = this.Location;
mEditor.Width = this.Width;
mEditor.Font = this.Font;
mEditor.Text = this.Text;
mEditor.SelectionLength = this.Text.Length;
mEditor.Leave += new EventHandler(mEditor_Leave);
this.Parent.Controls.Add(mEditor);
this.Parent.Controls.SetChildIndex(mEditor, 0);
mEditor.Focus();
}
base.OnDoubleClick(e);
}
void mEditor_Leave(object sender, EventArgs e) {
this.Text = mEditor.Text;
mEditor.Dispose();
mEditor = null;
}
protected override void Dispose(bool disposing) {
if (disposing && mEditor != null) mEditor.Dispose();
base.Dispose(disposing);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1603 次 |
最近记录: |