我正在尝试创建一个动态的表格布局,该布局创建一项技能,并为该技能设置1级和一个增加减少按钮。我正在努力让按钮访问级别标签。我考虑过要找到被单击的按钮的位置,但可以弄清楚该怎么做。
预先,谢谢。
示例:
这是我到目前为止所拥有的:
private void skilladded(object sender, EventArgs e)
{
int i = 1;
int[] position= { 0,0};
bool test = false;
//string select;
int k=0;
for (i=1;i<=skillstableLayoutPanel.RowCount;i++)
{
Control c= skillstableLayoutPanel.GetControlFromPosition(0,i);
if (c!=null&&addskillswin.selected==c.Text)
{
test = true;
k = i;
break;
}
else if(c==null)
{
k = i;
break;
}
}
if (test==false)
{
Label newskill = new Label();
Label newskilllvl = new Label();
TableLayoutPanel buttontable = new TableLayoutPanel();
Button up = new Button();
Button down = new Button();
buttontable.ColumnCount = 2;
buttontable.RowCount = 1;
buttontable.RowStyles.Add(new RowStyle(SizeType.Percent,100f));
buttontable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,50f));
buttontable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50f));
buttontable.Margin = new Padding(0,0,0,0);
buttontable.Dock = DockStyle.Fill;
buttontable.Controls.Add(up, 0, 0);
buttontable.Controls.Add(down, 1, 0);
up.BackgroundImage = Properties.Resources.up;[enter image description here][2]
down.BackgroundImage = Properties.Resources.down;
up.BackgroundImageLayout=ImageLayout.Stretch;
down.BackgroundImageLayout = ImageLayout.Stretch;
newskill.Text = addskillswin.selected;
newskilllvl.Text = "1";
up.Margin = new Padding(0, 0, 0, 0);
down.Margin = new Padding(0, 0, 0, 0);
skillstableLayoutPanel.Controls.Add(newskill,0,k);
skillstableLayoutPanel.Controls.Add(newskilllvl, 1, k);
skillstableLayoutPanel.Controls.Add(buttontable, 2, k);
skillavaillabel.Text = (Convert.ToInt32(skillavaillabel.Text) - 1).ToString();
skillpointlvl = Convert.ToInt32(newskilllvl.Text);
up.MouseClick += new MouseEventHandler(skillup);
down.MouseClick += new MouseEventHandler(skilldown);
}
if (test==true)
{
skillstableLayoutPanel.GetControlFromPosition(1, k).Text = (Convert.ToInt32(skillstableLayoutPanel.GetControlFromPosition(1, k).Text) + 1).ToString();
skillavaillabel.Text = (Convert.ToInt32(skillavaillabel.Text) -1).ToString();
}
}
private void skillup(object sender, EventArgs e)
{
skillpointlvl++;
}
private void skilldown(object sender, EventArgs e)
{
skillpointlvl--;
}
答案 0 :(得分:0)
代替此:
up.MouseClick += new MouseEventHandler(skillup);
down.MouseClick += new MouseEventHandler(skilldown);
尝试这样的事情:
up.MouseClick += ((o, me) =>
{
int currentLevel = Int32.Parse(newskilllvl.Text);
currentLevel++;
newskilllvl.Text = currentLevel.ToString();
});
down.MouseClick += ((o, me) =>
{
int currentLevel = Int32.Parse(newskilllvl.Text);
currentLevel--;
newskilllvl.Text = currentLevel.ToString();
});
您的skillup
或skilldown
事件处理程序可能会处理每个发件人,并查看单击是从哪个按钮发出的,但是您必须唯一地命名每个按钮并进行大量字符串比较才能看到哪个按钮对应于哪个技能级别标签。上面的代码在每个按钮上添加了一个匿名处理程序,这使我们可以将被单击的按钮与相应的技能标签绑定在一起。
尽管如此,我个人不会像您一样将所有这些值存储在标签中。我要么将它们存储在表单的属性中,要么更好地存储在它们自己的类中。我还将所有这些逻辑放在表单之外的其他地方,例如在Presenter或Controller(或类库)中,并遵循MVC或MVP之类的设计模式。从长远来看,这将使维护和更改应用程序更加容易。
此外,考虑将驼峰式和帕斯卡式大小写用于变量名。所有小写变量都很难为有经验的程序员阅读。