【问题标题】:Windows Forms: choose from list without creating a formWindows 窗体:从列表中选择而不创建窗体
【发布时间】:2017-05-12 21:52:51
【问题描述】:

我正在编写一个实际上有时必须使用 GUI 元素的控制台应用程序。

特别是,从字符串列表中选择一个字符串需要通过 GUI 执行。它必须是这样的:

public static string SelectString(List<string> strings)
{
    string selectedString;

    // GUI part

    return selectedString;
}

是否可以像使用FolderBrowserDialog 这样的方式来实现它?例如,我使用下面的代码来选择一个文件夹:

public static string SelectFolder(string description)
{
    using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
    {
        folderBrowserDialog.Description = description;

        return folderBrowserDialog.ShowDialog() == DialogResult.OK
            ? folderBrowserDialog.SelectedPath
            : null;
    }
}

我知道ListBox,但它需要创建一个表单。

有什么想法吗?

【问题讨论】:

  • 您可以在运行时动态创建表单。
  • @RezaAghaei 我明白了,但是我必须设置尺寸、位置和所有其他东西。我想使用像FolderBrowserDialogOpenFileDialog 这样的轻量级的东西。还是我错了?
  • @DfM 你是对的,你需要设置一些项目。我认为没有内置项目可以满足您的需求。如果它是一个非常简单的形式,它应该不会太难。
  • 为什么不直接将表单添加到您的控制台应用程序(这不是问题)并调用该表单?这样您就不必对所有细节进行硬编码。

标签: c# .net winforms user-interface


【解决方案1】:

您可以直接在代码中创建表单。这是一个非常简单的例子。您可能想要添加一个OK 按钮。

Form frm = new Form();
ListBox listbox1 = new ListBox();
frm.Controls.Add(listbox1);
listbox1.Dock = DockStyle.Fill;
frm.ShowDialog();

int selectedIndex = listbox1.SelectedIndex;

为避免硬编码,您可以在控制台应用中添加 Form,然后调用表单:

Form1 frm = new Form1();
frm.ShowDialog();

在这种情况下,您可能需要将ListBoxModifier 属性设置为public,以便在对话框关闭后可以访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-31
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多