繁体   English   中英

如何为两个复选框设置不同的事件?

[英]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 checkboxAerospaceBlockset 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 checkboxAerospaceBlockset 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM