【问题标题】:Custom MessageBox DialogResult自定义 MessageBox DialogResult
【发布时间】:2017-04-11 17:34:17
【问题描述】:

我还有一个带有自定义按钮的自定义 c# MessageBox,并且我覆盖了 Show() 方法,这是我的大部分代码:

public partial class CustomMessageBox : Form
{
    public CustomMessageBox()
    {
        InitializeComponent();
    }
#region Variables
public static CustomMessageBox MsgBox;
public static DialogResult result;
public enum CustomMessageBoxButtons { Ok, OkCancel }
public enum CustomMessageBoxTxtBoxState { VisibleChar, PasswordChar, VisibleCharReadOnly }
#endregion

public static DialogResult Show(string text, string title, CustomMessageBoxButtons buttons)
{
    MsgBox = new CustomMessageBox();
    MsgBox.txtbox_content.Text = text;
    MsgBox.lbl_Title.Text = title;
    result = DialogResult.No;
    if (buttons == CustomMessageBoxButtons.Ok)
    {
        MsgBox.btn_ok.Location = new Point(86, 70);
        MsgBox.btn_cancel.Visible = false;
    }
    MsgBox.ShowDialog();
    return result;
}

这里是自定义按钮的事件

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

private void btn_cancel_Click(object sender, EventArgs e)
{
    this.DialogResult = DialogResult.Cancel;
}
private void btn_close_Click(object sender, EventArgs e)
{
    this.Close();
}

问题来了

private void flatButton1_Click(object sender, EventArgs e)
{
    if (CustomMessageBox.Show("Title", "TITLEEE", CustomMessageBox.CustomMessageBoxButtons.OkCancel) ==**CustomMessageBox.MsgBox.result.Yes**)
    {
        CustomMessageBox.Show("Aceptaste", "AGREED", CustomMessageBox.CustomMessageBoxButtons.Ok);
    }
    else
    {
        CustomMessageBox.Show("Rechazaste", "dENIED", CustomMessageBox.CustomMessageBoxButtons.Ok);
    }
}
#endregion

当我调用我的 messageBox 时,它会在 CustomMessageBox.MsgBox.result.Yes 上抛出一个错误,说

无法使用 WinForms 实例引用访问,而是使用类型 Name 来访问 QualifyIt

那么我该怎么办?

【问题讨论】:

    标签: c# winforms error-handling messagebox


    【解决方案1】:

    您没有将 Show 方法的结果与 DialogResult 进行比较。

    而不是使用

    if (CustomMessageBox.Show("Title", "TITLEEE", CustomMessageBox.CustomMessageBoxButtons.OkCancel) == CustomMessageBox.MsgBox.result.Yes)
    

    尝试使用

    if (CustomMessageBox.Show("Title", "TITLEEE", CustomMessageBox.CustomMessageBoxButtons.OkCancel) == DialogResult.Yes)
    

    【讨论】:

    • 完成了,但根本不起作用,DialogResult.Yes 似乎被引用到存储在我的主窗体中的本地 DialogResult 枚举,而不是我的 MessageBox 之一,因此使用 DialogResult.Yes 完成的任何表达式都将不适用于 MyMessageBox,
    • 嗯,你的Show 方法的返回类型是DialogResult。所以Show方法给出的返回值只能和DialogResult枚举成员比较。
    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多