ListView - finding the non selected item
Posted by: Mark Shurmer
Eh?
What I mean by the title is that sometimes when you are using a ListView, you want to find out the row that was used rather than the selected row.
The most likely scenario for this is when you have a button (or similar) as a column in the ListView. You want to be able to respond to the button click event and do something in relation to the row that it was clicked on.
Now you may (or may not) know that when you click on a button in this scenario, the row is not selected. This means that you cannot rely on using the currently selected item in the listview.
What you need to do is find the item pertaining to the row of the button that has been clicked. Actually this is quite easy because the button is part of the visual tree for the row, so you can just traverse up the visual tree to find it!
An example of how you would do this is:
private void btnAddSymbol_Click(object sender, RoutedEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is ListViewItem)) { dep = VisualTreeHelper.GetParent(dep); }
if (dep == null)
return;
SymbolList item = lvSystemWatchList.ItemContainerGenerator.ItemFromContainer(dep) as SymbolList;
if(item != null)
// do something
}



You must be logged-in to post a comment. Log-in/Register