Search code examples
wpflistboxitem

How to cast a ListBoxItem to the class bound to the list?


I have a ListBox with a list of Buddies bound to the class Buddy {String name; String message}

When the user clicks an item I get the clicked item by handling the PreviewMouseDown event:

var item = ItemsControl.ContainerFromElement(lb, e.OriginalSource as DependencyObject) as ListBoxItem;

The problem is that I cannot convert item to Buddy item: if I try to cast with

Buddy b=(Buddy)item

I get an error like cannot convert type ListBoxItem to Buddy

How can I make a cast to Buddy class?


Solution

  • it should be actually...

    Buddy b = (Buddy)item.DataContext;
    

    Does this help?