如何正确读取设计时设置的自定义控件属性值?
目前,行和列在控件的属性列表中设置(vs.net as 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;
}
}
}
}
答案 0 :(得分:1)
最终,无论何时属性Rows / Columns发生变化,您都希望重新制作网格。所以你应该有一个重新制作网格的方法,并在设置属性时调用它。
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...