繁体   English   中英

c# Forms - 将数组公开给属性编辑器以进行自定义控制

[英]c# Forms - Expose an array to the properties editor for custom control

我有一个自定义控件,我想在其中输入用户可以使用属性编辑器编辑的字符串列表/数组/集合。 我有代码,您可以在其中使用属性编辑器编辑数组,但在启动时数组始终为空。

    string[] _validDescriptions = new string[] { };
    [Description("Valid descriptions to select from"), Category("Behavior")]
    public string[] ValidDescriptions
    {
        get 
        {
            if (_validDescriptions == null)
                return new string[0];
            else
                return _validDescriptions; 
        }
        set 
        {
            _validDescriptions = value;
        }
    }

该属性确实出现在编辑器中,我可以添加值,但在运行时它始终为空

在此处输入图像描述

发现问题,物业工作正常。 我试图在构造函数中引用为空的属性。 如果我用 Load 事件引用它,它可以正常工作。

    string[] _validDescriptions = new string[] { };
    [Description("Valid descriptions to select from"), Category("Behavior")]
    public string[] ValidDescriptions
    {
        get
        {
            if (_validDescriptions == null)
                return new string[0];
            else
                return _validDescriptions;
        }
        set
        {
            _validDescriptions = value;
        }
    }
    public ArrayControl()
    {
        InitializeComponent();

        // Added 4 values using the properties editor
        Console.WriteLine("Count in Constructor: " + _validDescriptions.Length); // will be 0
    }

    private void ArrayControl_Load(object sender, EventArgs e)
    {
        Console.WriteLine("Count in Load: " + _validDescriptions.Length); // will be correct value
    }

    private void button1_Click(object sender, EventArgs e)
    {
        richTextBox1.Clear();

        foreach (string s in _validDescriptions)
        {
            richTextBox1.AppendText(s + "\n"); // correctly populates text box.
        }
    } 

只是您发现的问题的附录:
在设计器中设置的值被简单地写入表单的InitializeComponent()方法(用户控件所在的表单)。
您可以在那里查看它 - 看看为什么它在控件的构造函数中必须为空:

    private void InitializeComponent()
    {
        this.ucOne1 = new Test_Project.ucOne(); 
//↑↑ call to the UserControl's constructor
        this.SuspendLayout();
        // 
        // 
        // [... maybe other control inits]
        
        // ucOne1
        // 
        this.ucOne1.Location = new System.Drawing.Point(454, 301);
        this.ucOne1.Name = "ucOne1";
        this.ucOne1.Size = new System.Drawing.Size(416, 230);
        this.ucOne1.TabIndex = 1;
//↓↓ This is where the design-time-defined values are assigned:
        this.ucOne1.ValidDescriptions = new string[] {
    "Value1",
    "Value2",
    "Value3"};
    
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM