0

如何正确读取通过设计时设置的自定义控件属性的值?

目前,行和列是在控件的属性列表中设置的(vs.net 作为 ide),但是当从控件的构造函数中读取时,这两个属性都返回 0。我怀疑构造函数是在应用程序启动期间分配属性之前执行的。

这样做的正确方法是什么?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;

    namespace HexagonalLevelEditor.HexLogic{

        class HexGrid : System.Windows.Forms.Panel {

            public HexGrid() {
                for(int c = 0; c < this.Columns; ++c) {
                    for(int r = 0; r < this.Rows; ++r) {
                        HexCell h = new HexCell();
                        h.Width = 200;
                        h.Height = 200;
                        h.Location = new System.Drawing.Point(c*200, r*200);
                        this.Controls.Add(h);
                    }
                }
            }

            private void InitializeComponent() {
                this.SuspendLayout();
                this.ResumeLayout(false);
            }

            private int m_rows;
            [Browsable(true), DescriptionAttribute("Hexagonal grid row count."), Bindable(true)]
            public int Rows {
                get {
                    return m_rows;
                }

                set {
                    m_rows = value;
                }
            }

            private int m_columns;
            [Browsable(true), DescriptionAttribute("Hexagonal grid column count."), Bindable(true)]
            public int Columns { 
                get{
                    return m_columns;
                }

                set {
                    m_columns = value;
                }
            }
        }
    }
4

1 回答 1

1

最终,当任一属性行/列发生更改时,您真的想重新制作网格。所以你应该有一个方法来重新制作网格,并在设置属性时调用它。

public void RemakeGrid()
{
    this.ClearGrid();

    for(int c = 0; c < this.Columns; ++c)
    {
        for(int r = 0; r < this.Rows; ++r)
        {
            HexCell h = new HexCell();
            h.Width = 200;
            h.Height = 200;
            h.Location = new System.Drawing.Point(c*200, r*200);
            this.Controls.Add(h);
        }
    }
}

private int m_rows;

[Browsable(true), DescriptionAttribute("Hexagonal grid row count."), Bindable(true)]
public int Rows
{
    get
    {
        return m_rows;
    }
    set
    {
        m_rows = value;
        this.RemakeGrid();
    }
}

// Same goes for Columns...
于 2012-05-08T03:25:38.877 回答