我有一个字典(字符串,字符串),我使用字典值设置目录路径,并使用键为每个值设置描述。
例如:
Value of a random item of my dictionary: "C:\Test"
Key name of that item = "Test folder"
好吧,现在在我的应用程序中,我可以选择是否更喜欢显示描述或完整目录路径,这就是问题所在......
一些图像来理解它:
1 - 我在这里存储/管理我的字典项目:
2 - 我可以调整此复选框以在组合框中显示字典键或字典值(您将在下一张图片中看到):
3 - 描述复选框被选中,然后描述显示在组合框中,当我添加一个项目时,它会与选定的combobox.text一起添加(可以是描述或完整路径)
4 - 现在我取消选中描述复选框,我想要更改列表视图的描述,就像我将组合框的描述更改为等效的完整路径一样(但我更改组合框名称的方法是重新加载字典因为是按字母顺序排序的所以......我不知道如何对列表视图子项做同样的事情)
我想记住你,listview 子项文本可以是描述,也可以是完整路径,所以我需要在这两种选择中进行这种改变思考。
...这是我的代码:
(请阅读评论)
' First of all
' "Item.SubItems(2).Text" can be the description or it can be the full path, so I need to do it with both alternatives
If ListView_Monitor.Items.Count <> 0 Then
For Each Item As ListViewItem In ListView_Monitor.Items
If ShowDescriptions Then ' Showdescription is a boolean var to show descriptions or full paths
' Description is stored in the "Dictionary.Key"
' I don't know how to get the key name of the item
' Item.SubItems(2).Text = Directories_SendTo.keys ... ...
' CType(Item.SubItems(2).Text, Directories_SendTo... ...)
ElseIf Not ShowDescriptions Then ' Don't show descriptions, I will show fullpaths
' Fullpath is stored in the "Dictionary.Value"
' Remember that "Item.SubItems(2).Text" can be the description or the fullpath
' So if "Item.SubItems(2).Text" is the description then this piece of code works, 'cause the dictionary keyname is the same as the description name
Item.SubItems(2).Text = Directories_SendTo(Item.SubItems(2).Text)
' Here I need an alternative if "Item.SubItems(2).Text" is the directory path and not the description
End If
Next
End If
更新:
解决方案(暂时)...
我的问题是我是否可以改进这段代码(也许不要在字典内循环):
If ListView_Monitor.Items.Count <> 0 Then
For Each Item As ListViewItem In ListView_Monitor.Items
If ShowDescriptions Then ' Show descriptions
For Each value In Directories_SendTo.Values
If value = Item.SubItems(2).Text Then
Item.SubItems(2).Text = FindKeyByValue(Directories_SendTo, Item.SubItems(2).Text)
End If
Next
ElseIf Not ShowDescriptions Then ' Show fullpaths
For Each key In Directories_SendTo.Keys
If key = Item.SubItems(2).Text Then
Item.SubItems(2).Text = Directories_SendTo(key)
End If
Next
End If
Next
End If
Public Function FindKeyByValue(Of TKey, TValue)(dictionary As Dictionary(Of TKey, TValue), value As TValue) As TKey
For Each pair As KeyValuePair(Of TKey, TValue) In dictionary
If value.Equals(pair.Value) Then Return pair.Key
Next
' Throw New Exception("The value is not found in the dictionary.")
Return Nothing
End Function