Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView: getting an actual item object from ListViewItem

Tags:

c#

listview

wpf

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.

like image 893
Violet Giraffe Avatar asked Jan 17 '26 23:01

Violet Giraffe


1 Answers

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.

like image 193
Dennis Avatar answered Jan 20 '26 13:01

Dennis