我有一个小程序,它在加载时生成四个动态按钮flowLayoutPanel1
和一个静态保存按钮。
我的目标是保存动态按钮颜色,以便在重新加载或再次打开表单时,动态按钮的颜色会以与保存时相同的状态重新加载。
下面我将包含我的代码,该代码已被注释以演示我的尝试。我正在使用一个xml
文件来保存按钮状态并包含一个保存状态的类。但是,如果创建我的按钮以静态保存,我使用的方法可以正常工作。(我只用一个静态按钮尝试过)
接口: 持有状态的类:
public class MyFormState
{
public string ButtonBackColor { get; set; }
}
表格代码:
public partial class Form1 : Form
{
//Form Member
MyFormState state = new MyFormState();
Button btn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//loading xml file if it exists
if (File.Exists("config.xml"))
{
loadConfig();
}
//Genrating dynamic buttons
// flowLayoutPanel1.Controls.Clear();
for (int i = 0; i <= 3; ++i)
{
btn = new Button();
btn.Text = " Equation " + i;
flowLayoutPanel1.Controls.Add(btn);
//click event of buttons
btn.Click += new EventHandler(btn_Click);
}
btn.BackColor = System.Drawing.ColorTranslator.FromHtml(state.ButtonBackColor);
}
//method to load file
private void loadConfig()
{
XmlSerializer ser = new XmlSerializer(typeof(MyFormState));
using (FileStream fs = File.OpenRead("config.xml"))
{
state = (MyFormState)ser.Deserialize(fs);
}
}
//saving the xml file and the button colors
private void writeConfig()
{
using (StreamWriter sw = new StreamWriter("config.xml"))
{
state.ButtonBackColor = System.Drawing.ColorTranslator.ToHtml(btn.BackColor);
XmlSerializer ser = new XmlSerializer(typeof(MyFormState));
ser.Serialize(sw, state);
}
}
int count = 0;
//backcolor change
void btn_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (count == 0)
{
button.BackColor = Color.Red;
count++;
}
else if (count == 1)
{
button.BackColor = Color.Blue;
count--;
}
}
//save file
private void btnSave_Click(object sender, EventArgs e)
{
writeConfig();
}
}
关于我应该改变什么以使其对我有用的任何建议?谢谢