FormClosing 事件被多次调用

FormClosing event being called multiple times

我有一个组合框来设置用户文化:

如果我更改 Culture 值 x 次,当用户尝试退出时,FormClosing 方法将被触发 x 次。

这是我的 FormClosing 事件:

    private void FrmParent_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show(this, Properties.Resources.msgExit, this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
            e.Cancel = true;
    }

这是我的组合框值更改事件:

    void cbCulture_ToolValueChanged(object sender, ToolEventArgs e)
    {
        ComboBoxTool cbCulture = (ComboBoxTool)sender;
        var culture = cbCulture.Value.ToString();

        FormHelpers.SetCulture(culture);

        this.Controls.Clear();
        this.InitializeComponent();
        InitForm();
    }

我必须清理并初始化控件以将 UI 更改为新区域性,但是这样做我是否在 InitializeComponent() 中多次分配 FormClosing 事件?我怎样才能避免这种行为?

是因为InitializeComponent,在那个方法forms design modeproperties/events中设置的。所以每次它都会添加 FormClosing event 一个。为避免这种情况,请在 this.InitializeComponent();

上方添加此行
this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.FrmParent_FormClosing);

注意:它只解决了FormClosing事件问题

从 InitializeComponent 中删除添加 FormClosing 事件处理程序的行:

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmParent_FormClosing);

您可以手动执行此操作,也可以使用设计器删除处理程序。

然后,不要使用设计器添加此事件处理程序,而是手动添加它,例如通过在调用 InitializeComponent.

之后向构造函数添加相同的行

不过,调用 InitializeComponent 也会重新初始化您的 UI 状态。也许您可能会寻找其他解决方案,例如 this one(我没有亲自尝试过,也不能保证)。