【发布时间】:2010-02-22 08:29:54
【问题描述】:
有人知道我可以如何创建可编辑标签控件吗?我需要我的用户能够编辑标签(同时更改部分样式信息),但在网上任何地方都找不到有用的信息。
感谢任何帮助
谢谢
【问题讨论】:
标签: c# winforms controls label edit
有人知道我可以如何创建可编辑标签控件吗?我需要我的用户能够编辑标签(同时更改部分样式信息),但在网上任何地方都找不到有用的信息。
感谢任何帮助
谢谢
【问题讨论】:
标签: c# winforms controls label edit
您可以创建自定义控件(需要一些工作)。控件内部可以有一个标准的标签控件,当用户单击标签(或以某种方式进入编辑模式)时,您可以实例化一个文本框控件并将其显示在标签控件所在的位置。所以用户会得到标签控件被“转换”为文本框的错觉。用户可以在文本框中编辑标签文本,编辑完成后,您只需隐藏文本框并将更改应用于标签文本。
如果您还需要编辑样式,则必须显示一个包含所有可编辑设置的面板,而不是单个文本框。
【讨论】:
您可以简单地使用 TextBox 控件,当您需要它们时无法对其进行编辑。只需将它的 readOnly 属性设置为 true。
祝你有美好的一天
【讨论】:
间接制作。
例如注册双击事件并显示一个带有文本框的无边框表单,用户可以在其中输入新名称。示例:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication
{
public partial class LabelEditor : Form
{
private System.Windows.Forms.TextBox textBox;
public LabelEditor()
{
InitializeComponent();
this.textBox = new System.Windows.Forms.TextBox();
this.textBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox.Location = new System.Drawing.Point(0, 0);
this.textBox.Name = "textBox";
this.textBox.Size = new System.Drawing.Size(100, 20);
this.textBox.TabIndex = 0;
this.textBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDown);
this.AutoSize = true;
this.ClientSize = new System.Drawing.Size(100, 20);
this.Controls.Add(textBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MinimumSize = new System.Drawing.Size(100, 20);
this.Name = "LabelEditor";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
}
public override string Text
{
get
{
if (textBox == null)
return String.Empty;
return textBox.Text;
}
set
{
textBox.Text = value;
ResizeEditor();
}
}
private void ResizeEditor()
{
var size = TextRenderer.MeasureText(textBox.Text, textBox.Font);
size.Width += 20;
this.Size = size;
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.Escape:
DialogResult = DialogResult.Cancel;
this.Close();
break;
case Keys.Return:
DialogResult = DialogResult.OK;
this.Close();
break;
}
}
}
}
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication
{
public partial class Form1 : Form
{
private Label EditableLabel;
public Form1()
{
InitializeComponent();
this.EditableLabel = new System.Windows.Forms.Label();
this.EditableLabel.AutoSize = true;
this.EditableLabel.Location = new System.Drawing.Point(102, 81);
this.EditableLabel.Text = "Click me to change...";
this.EditableLabel.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.LabelMouseDoubleClick);
this.Controls.Add(this.EditableLabel);
}
private void LabelMouseDoubleClick(object sender, MouseEventArgs e)
{
var label = sender as Label;
if (label != null)
{
var editor = new LabelEditor();
editor.Location = label.PointToScreen(new Point(e.X + 5, e.Y + 5));
editor.Text = label.Text;
if (DialogResult.OK == editor.ShowDialog())
{
label.Text = editor.Text;
}
}
}
}
}
【讨论】:
如果您还想提供编辑样式属性的可能性,您可以在表单上使用PropertyGrid 控件(与在 Visual Studio 中用于编辑控件属性的控件相同)。
【讨论】: