【发布时间】:2011-03-24 03:01:53
【问题描述】:
如果按下消息框上的“是”按钮,我会怎么说?在 C# 中。
【问题讨论】:
标签: c# button messagebox
如果按下消息框上的“是”按钮,我会怎么说?在 C# 中。
【问题讨论】:
标签: c# button messagebox
您对MessageBox.Show 的调用需要传递MessageBoxButtons.YesNo 以获得Yes/No 按钮而不是OK按钮。
将该调用的结果(将阻止执行直到对话框返回)与DialogResult.Yes....进行比较。
if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
// user clicked yes
}
else
{
// user clicked no
}
【讨论】:
如果你真的想要是和否按钮(假设是 WinForms):
void button_Click(object sender, EventArgs e)
{
var message = "Yes or No?";
var title = "Hey!";
var result = MessageBox.Show(
message, // the message to show
title, // the title for the dialog box
MessageBoxButtons.YesNo, // show two buttons: Yes and No
MessageBoxIcon.Question); // show a question mark icon
// the following can be handled as if/else statements as well
switch (result)
{
case DialogResult.Yes: // Yes button pressed
MessageBox.Show("You pressed Yes!");
break;
case DialogResult.No: // No button pressed
MessageBox.Show("You pressed No!");
break;
default: // Neither Yes nor No pressed (just in case)
MessageBox.Show("What did you press?");
break;
}
}
【讨论】:
if(DialogResult.OK==MessageBox.Show("Do you Agree with me???"))
{
//do stuff if yess
}
else
{
//do stuff if No
}
【讨论】:
MessageBoxButtons 参数的Show 重载之一,则MessageBox 将不会有除确定之外的任何按钮,因此else 部分将永远不会触发。即使通过右上角的关闭框关闭它,结果也是DialogResult.OK。
.NET 4.5 正确答案的更新版本是。
if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxImage.Question)
== MessageBoxResult.Yes)
{
// If yes
}
else
{
// If no
}
此外,如果您想将按钮绑定到视图模型中的命令,您可以使用以下命令。这与 MvvmLite 兼容:
public RelayCommand ShowPopUpCommand
{
get
{
return _showPopUpCommand ??
(_showPopUpCommand = new RelayCommand(
() =>
{
// Put if statement here
}
}));
}
}
【讨论】:
检查一下:
if (
MessageBox.Show(@"Are you Alright?", @"My Message Box",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//YES ---> Ok IM ALRIGHHT
}
else
{
//NO --->NO IM STUCK
}
问候
【讨论】:
这种方式可以在 MessageBox 窗口中按“YES”或“NO”按钮时检查条件。
DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo);
if (d == DialogResult.Yes)
{
//Contents
}
else if (d == DialogResult.No)
{
//Contents
}
【讨论】: