WinForms ListView - 从选定的字符串项中获取源对象

时间:2015-10-12 10:34:10

标签: c# winforms listview

我正在WinForms中构建一个简单的语言学习帮助应用程序。其中一个模块是字典。它由“集合”组成,单词存储在一个集合中。用户可以创建一组新的单词并将其中的一些存储在其中。

我正在使用列打印ListView中所选的一个或多个集合中的所有单词。检查CheckedListBox中的一个或多个集合后,列表将清除并打印单词(作为字符串变量)。

当列出的单词被检查时,会出现麻烦,并且用户想要编辑其中一个列出的单词。我不能使用索引(例如List项目的index等于Set中的单词项目),因为那些List字符串项目来自不同的集合。

有没有办法从ListView项中获取源对象?我没有在列表中添加对象但只添加了一些变量,但它们是否以某种方式连接?

感谢您的帮助。 干杯!

编辑:解释为什么我设置Tag不是解决方案: 所有集都存储在List<DictionarySet> dictionarySets中。每个集合都包含List<Word> words,其中存储了单词。

如何填写ListView:

private void UpdateList()
        {
            wordsListView.Items.Clear();
            List<Word> currentSetWordList;

            foreach (DictionarySet ds in setCheckedListBox.CheckedItems) //List<DictionarySets> dictionarySets inserted, DisplayMember set to its Name property

            {
                currentSetWordList = ds.words;
                foreach (Word w in currentSetWordList) 
                {
                    ListViewItem newItem = new ListViewItem("--"); //for now a string, later an enum
                    newItem.Tag = ds;
                    newItem.SubItems.Add(w.GermanTranslation); //string property
                    newItem.SubItems.Add(w.PolishTranslation); //string property

                    wordsListView.Items.Add(newItem);
                }
            }
        }

在这种情况下,程序循环遍历每个Set及其单词列表并打印单词。他们的标签到处都是DictionarySet。

1 个答案:

答案 0 :(得分:0)

您可以使用Tag上的ListViewItem属性。标签属性:

  

获取或设置一个对象,该对象包含与项目关联的数据。

简而言之,当您创建列表视图的每个项目时,可以将对象添加为标记。这样,当用户选择项目时,您就可以将其取回。

有关详细信息,请参阅MSDN