1

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];
Stavros
  • 147
  • 2
  • 14
  • When you add strings to the Items collection, it will not magically contain ListViewItems. Why do you want to get a ListViewItem at all, instead of just the item string you've added? – Clemens Mar 16 '18 at 16:20
  • I want to get the ListViewItem because my ListView has a Item Template with a checkbox, and I want to set the specific ListViewItem's checkbox.IsChecked property to true. – Stavros Mar 16 '18 at 16:49
  • You should bind the ListView's ItemsSource to a collection of objects with a string and a bool property. In the ItemTemplate, bind the CheckBox to the bool item property. Accessing ListViewItems by the ItemContainerGenerator is a hacky solution for whta should actually be done by data binding to an appropriate view model. – Clemens Mar 16 '18 at 17:36

1 Answers1

0

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.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • I Found that when I tried: `myListView.Items.Add("one"); myListView.Items.Add("two"); ListViewItem item = myListView.ItemContainerGenerator.ContainerFromIndex(myListView.Items.Count - 1) as ListViewItem;` the item var still came up as null. What I have to do is add the item to the ListView then wait for the ItemContainerGenerator_StatusChanged to changed to Generated, then do what I want to do to the ListBoxItem in that event handler. – Stavros Mar 16 '18 at 17:03
  • Yes, the container has to be created before you can get a reference to it. – mm8 Mar 19 '18 at 14:54