【问题标题】:Name and Value (path) for ListBoxListBox 的名称和值(路径)
【发布时间】:2018-06-21 10:39:11
【问题描述】:

作为 C# 中的新手,我正在寻找一种简单的方法来添加 10 个名称,每个名称都有不同的值(在本例中为路径)。我搜索了又搜索,我认为它不能用 C# Windows Forms 来完成,但我必须更改为 WPF ?

一定是这样的

listBox1.Items.add(new ListBoxItem("Computer 1", "C:\001"));
listBox1.Items.add(new ListBoxItem("Computer 2", "C:\002"));

但是 Windows 窗体不支持 ListBoxItem 吗?

【问题讨论】:

标签: c# winforms listbox


【解决方案1】:

当然在 Windows 窗体中支持它!

你有两个选择:

使用匿名对象:

listBox1.Items.Add(new { Name = "Computer 1", Path = "C:\\001" });
listBox1.Items.Add(new { Name = "Computer 2", Path = "C:\\002" });

这会显示得很丑。

或者通过声明你自己的类:

public class MyListObject
{
    public string Name { get; set; }
    public string Path { get; set; }

    public MyListObject(string name, string path)
    {
        Path = path;
        Name = name;
    }
    // to nicely display it in List Box
    public override string ToString()
    {
        return Name + " " + Path;
    }
}

然后像这样使用它:

listBox1.Items.Add(new MyListObject("Computer 1", "C:\\001"));
listBox1.Items.Add(new MyListObject("Computer 2", "C:\\002"));

继续使用第二种方法,考虑到@MattWhitfield 的回答,将此代码添加到您的应用中以查看其工作原理:

// display Names of objects, this way you don't need to override ToString() method in your class
listBox1.DisplayMember = "Name";

listBox1.Items.Add(new MyListObject("Computer 1", "C:\\001"));
listBox1.Items.Add(new MyListObject("Computer 2", "C:\\002"));

// select first item just for example
listBox1.SelectedIndex = 0;
MessageBox.Show((listBox1.SelectedItem as MyListObject).Path);

【讨论】:

  • 谢谢!帮了我很多。但现在我想添加一个按钮来打开文件夹.. 他现在拿走了两个数组。他有可能只是得到字符串 Path 吗? int selectedIndex = listBox1.SelectedIndex;对象 selectedItem = listBox1.SelectedItem; System.Diagnostics.Process.Start(selectedItem.ToString());
  • @Mike 查看更新的答案 :) 并接受,如果它解决了问题。或者,您可以投票。
  • 解决了!谢谢:)
【解决方案2】:

您可以将任何 C# 对象添加到列表框 Items 集合中,然后设置 ValueMemberDisplayMember 属性来告诉列表框您的对象中的哪些成员代表值以及要显示哪些成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多