[英]How I can have different events for two check boxes?
我有兩部分代碼:
private void Simulink_CheckedChanged_1(object sender, EventArgs e)
{
string installerfilename = path + "installer.ini";
string installertext = File.ReadAllText(installerfilename);
var lin = File.ReadLines(Path.Combine(path, "installer.ini")).ToArray();
CheckBox cb = sender as CheckBox;
if (cb.Checked)
{
var product = lin.Select(line => Regex.Replace(line, "product=all", "#product=all"));
var product_tool = product.Select(line => Regex.Replace(line, "#product=Simulink", "product=Simulink"));
File.WriteAllLines(installerfilename, product_tool);
}
else if (!cb.Checked)
{
return;
}
}
private void AerospaceBlockset_CheckedChanged(object sender, EventArgs e)
{
string installerfilename = path + "installer.ini";
string installertext = File.ReadAllText(installerfilename);
var lin = File.ReadLines(Path.Combine(path, "installer.ini")).ToArray();
CheckBox cb1 = sender as CheckBox;
if ( cb1.Checked )
{
var product = lin.Select(line => Regex.Replace(line, "product=all", "#product=all"));
var product_tool = product.Select(line => Regex.Replace(line, "#product=AerospaceBlockset", "product=AerospaceBlockset"));
File.WriteAllLines(installerfilename, product_tool);
}
else if (!cb1.Checked)
{
return;
}
}
第二個功能與第一個功能相同,換句話說,如果我選中Simulink checkbox
或AerospaceBlockset checkbox
或者在installer.ini文件中兩者都將產生相同的結果:
product=all => #product=all
#product=Simulink=> product=Simulink
要正常工作,需要出現在instaler.ini
文件中:
product=all => #product=all
#product=Simulink=> product=Simulink
如果已選中Simulink checkbox
,並且:
product=all => #product=all
#product=AerospaceBlockset=> product=AerospaceBlockset
如果AerospaceBlockset checkbox
了AerospaceBlockset checkbox
。
我該怎么做?
您可以將兩個復選框的tag屬性設置為所需的字符串,然后更改行
var product_tool = product.Select(line => Regex.Replace(line, "#product=AerospaceBlockset", "product=AerospaceBlockset"));
至
var product_tool = product.Select(line => Regex.Replace(line, "#product=" + ((sender as CheckBox).Tag as string), "product=" + ((sender as CheckBox).Tag as string)));
最后,對兩個復選框使用相同的功能。
在窗體的構造函數中(假設使用WinForms),可以為復選框連接事件,如下所示:
Simulink.CheckedChanged += Simulink_CheckedChanged_1;
AerospaceBlockset.CheckedChanged += AerospaceBlockset_CheckedChanged;
(您可能必須刪除設計器中的條目,因此您不必兩次調用這些方法。)
這樣,復選框將執行其各自的事件。 由於它們的動作基本相同,因此您可以考慮將邏輯提取到另一個方法中,然后使用合適的參數進行調用:
private void Simulink_CheckedChanged_1(object sender, EventArgs e)
{
ProcessIniFile("Simulink");
}
在ProcessIniFile
您將在事件方法中執行當前操作,但是將硬編碼值替換為傳入的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.