目的是将列表视为“名称”列表。

这是字典:

class Scripts
    {
        public Dictionary<int, Script> scripts = new Dictionary<int, Script>();
        ...
    }

这是我所追求的属性“名称”:
class Script
    {
        public string name { get; set; }
        ...
    }

这是问题所在:
public partial class MainForm : Form
{
    Scripts allScripts;

    public MainForm()
    {
        InitializeComponent();
        allScripts = new Scripts();
        setupDataSources();
    }

    private void setupDataSources()
    {
        BindingSource ketchup = new BindingSource(allScripts.scripts, null);
        //THIS LINE:
        listBoxScripts.DisplayMember = allScripts.scripts["Key"].name.ToString();
        listBoxScripts.ValueMember = "Key";
        listBoxScripts.DataSource = ketchup;
    }
    ...
}

我只是想不出如何使这条线正常工作!非常感谢您的建议!

谢谢

最佳答案

您可以绑定(bind)到Value并重写ToString类中的Script方法。

private void setupDataSources()
{
    BindingSource ketchup = new BindingSource(allScripts.scripts, null);
    listBoxScripts.DisplayMember = "Value";
    listBoxScripts.ValueMember = "Key";
    listBoxScripts.DataSource = ketchup;
}

脚本类:
class Script
{
    public string name { get; set; }

    public override string ToString()
    {
        return name;
    }
}

关于C#我可以在字典中将对象的属性显示为ListControl.DisplayMember吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15817739/

10-11 03:56