在表格的顶部
Dictionary<string, string> FileList = new Dictionary<string, string>();
在构造函数中
public Form1()
{
InitializeComponent();
if (System.IO.File.Exists(Path.Combine(path, "test.txt")))
{
string g = System.IO.File.ReadAllText(Path.Combine(path, "test.txt"));
FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
listBox1.DataSource = FileList.ToList();
}
取而代之的是:
listBox1.DataSource = FileList.ToList();
然后我将在listBox中看到例如"hello“、"d:\test\test1.txt”
我希望在listBox中只有:“你好”
我不想更改FileList,而是要更改将从FileList添加到listBox的内容,这只是左侧。
另一个问题可能是listBox所选索引的问题:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = ((ListBox)sender).SelectedItem;
var itemCast = (KeyValuePair<string, string>)item;
pictureBox1.Image = System.Drawing.Image.FromFile(itemCast.Value);
}
一方面,我不希望在listBox中看到右侧的值,另一方面,我希望所选的索引事件能够正常工作。
发布于 2022-10-14 05:01:39
字典将键映射到值。您所称的“左部分/侧”实际上是关键,而另一个元素是值。
C# Dictionary
有一个属性:Keys
,它只返回字典中的键(例如,"hello"
字符串)。
因此,您可以使用:
listBox1.DataSource = FileList.Keys.ToList();
注意,如果您只需要值(例如"d:\test\test1.txt"
等),那么Dictionary
具有类似的属性:。
发布于 2022-10-14 05:11:24
我猜,当用户选择一个键时,您会希望得到相应的值。在这种情况下,不只是绑定键,而是绑定整个Dictionary
。
myListBox.DisplayMember = "Key"
myListBox.ValueMember = "Value"
myListBox.DataSource = myDictionary.ToArray()
每个项目都是一个KeyValuePair
,它具有Key
和Value
属性。上面的代码将显示键,然后,当用户选择一个项时,您可以从SelectedValue
属性中获得相应的值。
注意,这样的数据绑定需要一个IList
,而Dictionary
只实现ICollection
。因此,您需要调用ToArray
或ToList
来创建用于绑定的IList
。
https://stackoverflow.com/questions/74064447
复制相似问题