我对 C# 了解不多,所以如果我的问题在其他地方得到解答,我提前表示歉意。我不知道要搜索什么。
我正在 Windows 窗体中制作井字游戏。我是这样设置的:每个单元格都有 2 个按钮(x 和 o)和两个标签(X 和 O)。单击其中一个按钮会将相应标签的可见属性更改为 true,同时禁用(enable=false)相反的按钮被选中。总共有 9 个单元格。我还有一个菜单按钮(重置),单击该按钮将启用所有按钮并隐藏所有标签,以便可以重新玩游戏。
我正在寻找一种方法来重置我想要的所有项目,而不必为每个项目单独键入代码。有没有办法将这些项目组合在一起,以便可以用最少的代码同时触发它们?
源代码不完整,因为我还在编写程序。我已经发布了三个单元格的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tick_Tack_Toe
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void xButton1_Click(object sender, EventArgs e)
{
xLabel1.Visible = true;
oButton1.Enabled = false;
}
private void oButton1_Click(object sender, EventArgs e)
{
oLabel1.Visible = true;
xButton1.Enabled = false;
}
private void xButton2_Click(object sender, EventArgs e)
{
xLabel2.Visible = true;
oButton2.Enabled = false;
}
private void oButton2_Click(object sender, EventArgs e)
{
oLabel2.Visible = true;
xButton2.Enabled = false;
}
private void resetToolStripMenuItem_Click(object sender,
EventArgs e)
{
xButton1.Enabled = true;
oButton1.Enabled = true;
xButton2.Enabled = true;
oButton2.Enabled = true;
xButton3.Enabled = true;
oButton3.Enabled = true;
xLabel1.Visible = false;
oLabel1.Visible = false;
xLabel2.Visible = false;
oLabel2.Visible = false;
xLabel3.Visible = false;
oLabel3.Visible = false;
}
}
}
最佳答案
执行此操作的一种方法是遍历控件集合。由于您似乎对控件的命名有一个标准,因此您可以首先将集合缩小到仅名称以“o”或“x”开头的那些。然后,你可以查看控件的类型,如果是标签你可以隐藏它,如果是按钮你可以启用它:
private void ResetControls()
{
foreach (Control control in this.Controls)
{
// Only look at controls whose names begin with 'o' or 'x'
if (control.Name.StartsWith("o") ||control.Name.StartsWith("x"))
{
// Hide it if it's a label
if(control.GetType() == typeof(Label))
{
control.Visible = false;
}
// Enable it if it's a button
else if (control.GetType() == typeof(Button))
{
control.Enabled = true;
}
}
}
}
您提到您所有的按钮和标签都在它们自己的面板控件内,它有自己的控件集合。所以你可以修改上面的代码,先搜索面板控件,然后在面板控件的控件集合中搜索按钮和标签:
private void ResetControls()
{
foreach (Control control in this.Controls)
{
if (control is Panel)
{
var panel = control as Panel;
foreach (Control panelControl in panel.Controls)
{
// Only look at controls whose names begin with 'o' or 'x'
if (panelControl.Name.StartsWith("o") || panelControl.Name.StartsWith("x"))
{
// Hide it if it's a label
if (panelControl is Label)
{
panelControl.Visible = false;
}
// Enable it if it's a button
else if (panelControl is Button)
{
panelControl.Enabled = true;
}
}
}
}
}
}
请注意,这只是一种可能的解决方案,但肯定不是最好的。通常,控件将在运行时创建,添加到某种集合(通常是一个名为 GameBoard
或类似的数组),然后全部通过代码放置在窗体上。他们的点击事件都将连接到同一个方法,该方法将根据控件名称或 Tag
字段中的某些数据做正确的事情。
关于c# - 将不同的东西组合在一起,以便使用最少的代码同时激活/停用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469268/