Search code examples
c#wpflistboxstackpanel

How can I get the name of the listbox that a stackpanel is in?


A stackpanel's dragOver event gives me access to the stackpanel as sender, but how can I get the name of the listbox that the stackpanel is in (stack panel is defined in the datatemplate). The reason for this is to ultimately access all of the other stackpanels in the list generated by the datatemplate so if I'm barking up the wrong tree here I'll appreciate an alternative way of accessing the other stackpanels. Thanks,

Dan.


Solution

  • Updated (working) answer

    You need to walk up the visual tree with VisualTreeHelper.GetParent on the StackPanel, and if necessary recurse over further parents, until you find the ListBox (use the as or is operator to detect that you have found it).

    For added convenience, or if you need to traverse the tree in other directions (which is a bit more involved), you can use a wrapper that exposes the traversal in a LINQy format such as this one.

    All this said, you might also want to take a look at How can I find WPF controls by name or type?.