开发者

How can I implement Apply button functionality in C# WinForms? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

How can I implement Apply button action开发者_如何学编程 in a Windows Forms dialog with C#?


Windows Forms doesn't make it particularly easy unless it is the dialog itself that takes care of the side-effects. Which isn't always common, it is usually done in the form that calls ShowDialog(), based on the return value.

No biggie though, add your own event to the form:

    public event EventHandler ApplyChanges;
    protected virtual void OnApplyChanges(EventArgs e) {
        var handler = ApplyChanges;
        if (handler != null) handler(this, e);
    }

    private void OKButton_Click(object sender, EventArgs e) {
        OnApplyChanges(EventArgs.Empty);
        this.DialogResult = DialogResult.OK;
    }

    private void ApplyButton_Click(object sender, EventArgs e) {
        OnApplyChanges(EventArgs.Empty);
    }

And the code in your main form could then look like this:

    private void ShowOptionsButton_Click(object sender, EventArgs e) {
        using (var dlg = new Form2()) {
            dlg.ApplyChanges += new EventHandler(dlg_ApplyChanges);
            dlg.ShowDialog(this);
        }
    }

    void dlg_ApplyChanges(object sender, EventArgs e) {
        var dlg = (Form2)sender;
        // etc..
    }


You can set the AcceptButton-Property of a Form to any button placed on the form. When the "Enter" key is pressed on the form, the Click-Event of the AcceptButton is raised.

Maybe this is what you are looking for.


In Windows, the "Apply" button generally sets whatever properties that the user has specified in the dialog without closing the dialog box. So it's basically the same thing as the "OK" button, except without a command to close the dialog box.

You can take advantage of that fact and consolidate all of the property-setting code in the event handler for the Apply button, then call that first whenever the OK button is clicked, but before you close the form:

public void ApplyButtonClicked(object sender, EventArgs e)
{
    //Set any properties that were changed in the dialog box here
    //...
}

public void OKButtonClicked(object sender, EventArgs e)
{
    //"Click" the Apply button, to apply any properties that were changed
    ApplyButton.PerformClick();

    //Close the dialog
    this.DialogResult = DialogResult.OK;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜