I'm adding items of my own class to ListView (the listview has bindings set up appropriately):
_listView.Items.Add(new ProblemsListItem());
I have a MouseDoubleClick handler which acquires a ListViewItem that was clicked:
void onProblemDoubleClick(object sender, MouseButtonEventArgs e)
{
ListViewItem item = FindVisualParent<ListViewItem, ListView>(e.OriginalSource as DependencyObject);
}
public static TParent FindVisualParent<TParent, TLimit>(DependencyObject obj) where TParent : DependencyObject
{
while (obj != null && !(obj is TParent))
{
if (obj is TLimit)
return null;
obj = VisualTreeHelper.GetParent(obj);
}
return obj as TParent;
}
My qestion is: how can I convert this ListViewItem to my ProblemsListItem object, or get this object from the item?
I've tried inheriting ProblemsListItem from ListViewItem. Then I can, of course, convert item to ProblemsListItem type in the handler, but this totally breaks ListView: all columns are empty, it's not being filled properly.
You can use ItemContainerGenerator to get data item:
var dataItem = yourListView.ItemContainerGenerator.ItemFromContainer(yourListViewItem);
but this code smells. I can't see any reasons to not to use data binding, and handle double click as executing of ICommand implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With