0
我有一個小程序,在加載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();
}
}
什麼我應該改變,因此任何建議它適合我嗎?謝謝
「但是,我使用的方法工作正常,如果創建我的按鈕來保存靜態。」那麼最新的問題,我不知道你是什麼問題。你能澄清嗎? – 2013-03-01 13:58:43
你的應用程序有4個按鈕,但是你的代碼沒有任何邏輯來處理4個按鈕。 (不僅用於序列化,還用於改變顏色) – Steve 2013-03-01 13:58:48