【问题标题】:The type 'System.Windows.Forms.Form' has no property named 'textBox1'“System.Windows.Forms.Form”类型没有名为“textBox1”的属性
【发布时间】:2015-03-11 09:55:54
【问题描述】:

正如人们在 cmets 中指出的那样,您永远不应该为真正的应用程序这样做,因为这是不好的做法。我只是想了解属性在 Visual Studio 中的实际工作方式,并且永远不会在真正的应用程序中这样做。

每当我尝试查看我创建的表单的设计时,都会收到此错误消息。我进入代码并将 textBox1 字段设置为 public 并添加了 getter 和 setter:

namespace WindowsFormsApplication2
{
    partial class Form2
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(85, 82);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 20);
            this.textBox1.TabIndex = 0;
            // 
            // Form2
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.textBox1);
            this.Name = "Form2";
            this.Text = "Form2";
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        #endregion
        public System.Windows.Forms.TextBox textBox1 { get; private set; }
    }
}

当我运行程序时,它编译并运行没有错误,并且显然声明了一个 textBox1 属性。为什么我使用属性而不是普通字段时 Visual Studio 会中断?

编辑:感谢您修复代码块,我正要自己这样做

【问题讨论】:

  • 与其用公共自动属性替换字段,不如添加一个属性来提供对设计器生成的字段的访问权限?
  • 你真的不应该尝试更改designer.cs文件..使用部分类的另一半
  • @GrawCube,我认为使用自动属性比为每个组件使用单独的属性更简洁。从理论上讲,这应该有效。我只是想知道为什么它没有。
  • @Sayse 我知道,但这更像是一个实验。如果我正在编写一个实际的应用程序,我永远不会这样做。

标签: c# visual-studio-2013 properties windows-forms-designer


【解决方案1】:

您收到此错误是因为您正在手动更改设计器生成的代码。 如果你在你的设计器中点击文本框,你可以通过设计器本身将它公开,然后你就不会遇到这个问题了。

【讨论】:

  • 我也可以把它变成财产吗?我试图让它从类外部访问,但仍然控制设置字段(并且不使用 Java 样式的 getter/accessor)。
  • 可以,因为 C# 使用部分类。但是不要在设计器生成的文件中这样做。右键单击设计器中的表单,然后选择查看代码。在那里您可以创建编辑框的属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 2011-08-26
  • 1970-01-01
  • 2023-03-05
  • 2018-07-21
  • 1970-01-01
相关资源
最近更新 更多