Search code examples
c#wpflistviewlistviewitem

wpf listviewitem returning null when initialized


this question seems like it should have a really trivial answer but I can't seem to figure out what is going on in my program.

I have a C# WPF application which is using a ListView. The ListView has a couple items in it which I added to it by doing this

myListView.Items.Add("one");
myListView.Items.Add("two");

Now I a trying to access the second ListViewItem in the ListView.

ListViewItem item = myListView.Items[myListView.Items.Count - 1] as ListViewItem;

The Error that is occurring is myListViewItem item is null and not retuning a ListViewItem.

I've noticed that when I type in the below code my var item is returning a string with the value of "two". so I do not see why I am not able to access the object as a ListViewItem.

var item = clv_TraceGroups.Items[clv_TraceGroups.Items.Count - 1];

Solution

  • myListView.Items[myListView.Items.Count - 1] returns a string, i.e. the actual item that you have added to the Items collection.

    You could get a reference to the ListViewItem container for this item using the ItemContainerGenerator:

    ListViewItem item = myListView.ItemContainerGenerator.ContainerFromIndex(myListView.Items.Count - 1) as ListViewItem;
    

    Note that this approach won't work if you have many items in the ListView and you are trying to get a reference to a container for an item that has been virtalized away for performance reasons though.

    You should probably ask yourself why you need a reference to the ListViewItem container. There are probably better ways to solve whatever you are tryng to do.