在 Winforms 项目 (Visual Studio 2010) 中使用ListView控件时,我注意到虽然我在列设计器中为其 ColumnHeaders的NamecolumnHeaderFoo.Name
属性分配了有意义的值,但调用在运行时会返回一个空字符串。这与其他控件的行为不同,例如在同一表单上,buttonOK.Name
yield "buttonOK"
。
这是我设置值的地方:
或者在这里,结果相同:
这是一个包含一列的 ListView 表单的设计器生成的代码:
namespace ColumnDemo
{
partial class Form1
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.listView1 = new System.Windows.Forms.ListView();
this.columnHeaderTest = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// listView1
//
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeaderTest});
this.listView1.Location = new System.Drawing.Point(12, 12);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(494, 149);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(411, 167);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(95, 43);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(518, 221);
this.Controls.Add(this.button1);
this.Controls.Add(this.listView1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ColumnHeader columnHeaderTest;
private System.Windows.Forms.Button button1;
}
}
我在按钮单击时添加了一些输出:
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Button: " + button1.Name);
Console.WriteLine("Column: " + columnHeaderTest.Name);
}
结果输出是:
Button: button1
Column:
另一个有趣的事实是,项目文件中没有一个包含我在任何地方以字符串常量形式给出的“名称”值;似乎 VS 专门使用这个值来命名成员变量。
如果我将Name属性设置为运行时,则该值将按预期保留。似乎我总是错误地假设表单设计器使用标记为“名称”的字段来分配名称属性。
有没有办法在设计时明确定义控件的名称(不是变量的名称)?