none
How to obtain ListView from ListViewItem? RRS feed

  • Question

  • As the subject says: how does one obtain the ListView from a ListViewItem?

    I thought there would be a ListViewParent property or something similar, but there is not...

     

    Code sample for context:

     

    Code Snippet

    private void fileList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)

    {

    ListViewItem lvi = sender as ListViewItem;

    if (lvi == null)

    return;

     

    // how to get access to the ListView this item belongs to?

    }

     

     

     

    Any help appreciated!

    Koen

     

    Wednesday, February 20, 2008 12:46 PM

Answers

  • This should do the trick:
    ListView listView = ItemsControl.ItemsControlFromItemContainer(listViewItem) as ListView;

    Hope this helps

    Friday, February 22, 2008 5:37 AM

All replies

  • Hi,

    ListViewItem contains property "ListView" which you look for:
    http://msdn2.microsoft.com/pl-pl/library/system.windows.forms.listviewitem.listview(en-us,VS.80).aspx

    Cheers,
       Jakub G
    Wednesday, February 20, 2008 12:59 PM
  • No it doesn't in my documentation. I think you are talking about a Windows Forms ListView, whereas I am using WPF and my ListView is from System.Windows.Controls.ListView, and I see no ListView property there.

     

    The strange thing is that when I debug, I can see a the ListViewItem's base class is ListBoxItem, and that base class seems to have a non-public property called ParentListBox, which is derived from ListView. But I can't access it...

     

    Anyone?

    Koen

     

    Wednesday, February 20, 2008 1:15 PM
  • you can use VisualTreeHelper.GetParent method and walk up the tree until you find the type you want

     

    Wednesday, February 20, 2008 1:49 PM
    Moderator
  • Hi,

    Sorry, my fault, I did not see that WPF Sad

    As i remeber there is a Parent (i do not have possibility to check this now) property which was taking you to the parent element.

    Cheers,
       Jakub G
    Wednesday, February 20, 2008 1:56 PM
  • This should do the trick:
    ListView listView = ItemsControl.ItemsControlFromItemContainer(listViewItem) as ListView;

    Hope this helps

    Friday, February 22, 2008 5:37 AM