用自己的命令制作类似消息框的表单

问题描述 投票:0回答:2

首先,我想说英语不是我的母语。 我在 Windows 窗体中有此窗体:

Form

使用此代码:

public partial class FormInput : Form
{
    public FormInput(string Content)
    {
        InitializeComponent();

        this.Text = Content;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //confirm
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //cancel
    }
}

现在,我尝试在 WPF 窗口中实现它。我想这样使用它:

string foo;

if (FormInput.Show("abc") == true)
{
    foo = [Form output as a string];
}

因此,我需要一个作为字符串的输入值和两个作为布尔值和字符串的输出值。 用户必须在文本框(textBox1)中输入内容,然后单击确认或按 Enter 键,然后窗口关闭。或者,用户可以按退出键或单击“取消”。我怎样才能做到这一点?

c# winforms messagebox
2个回答
0
投票

好的,我有答案了; 主窗口:

string output;

FormInput input = new FormInput("abc");
input.ShowDialog();
if (input.ReturnValueConfirm == true)
    output = input.ReturnValueText;

第二个窗口:

public string ReturnValueText { get; set; }
public bool ReturnValueConfirm { get; set; }

public FormInput(string Content)
{
    InitializeComponent();

    this.Text = Content;
}

private void button1_Click(object sender, EventArgs e) //confirm
{
    ReturnValueText = textBox1.Text;
    ReturnValueConfirm = true;
    this.Close();
}

private void button2_Click(object sender, EventArgs e) //cancel
{
    ReturnValueText = textBox1.Text;
    ReturnValueConfirm = false;
    this.Close();
}

感谢评论...


0
投票

您可以创建一个静态方法来创建并打开表单。让它返回一个布尔值告诉用户是否点击了“确定”,您可以通过

out
参数返回字符串值。

将按钮的

DialogResult
属性设置如下(我将按钮称为
btnOK
btnCancel
):

// You can do this in the properties window.
btnOK.DialogResult = DialogResult.OK;
btnCancel.DialogResult = DialogResult.Cancel;

当 TextBox 被调用

txtValue
时,你会得到:

using System;
using System.Windows.Forms;

public partial class InputBox : Form
{
    public InputBox()
    {
        InitializeComponent();
    }

    public static bool TryGetInput(string title, out string value, string defaultValue = null)
    {
        var dlg = new InputBox();
        dlg.Text = title;
        dlg.txtValue.Text = defaultValue;

        if (dlg.ShowDialog() == DialogResult.OK) {
            value = dlg.txtValue.Text;
            return true;
        } else {
            value = null;
            return false;
        }
    }
}

现在,你可以这样调用输入框:

if (InputBox.TryGetInput("Input required", out string value)) {
    //TODO: use 'value' here.
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.