0

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.

4 Answers4

2

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?.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Thanks a lot Jon, I'll take a look at these, the parent property solution doesn't seem to be working for me. –  Dec 19 '11 at 11:09
  • @DanielMcNulty: Sorry, I forgot about that... getting rusty. See the updated answer, you need to walk the *visual* tree. – Jon Dec 19 '11 at 11:12
  • PERFECT Jon!! Solved a problem that had me pulling my hair out there. Thanks mate. –  Dec 19 '11 at 11:16
1

Use the .Parent property to get the object that the current object is hosted in.

Adam
  • 16,089
  • 6
  • 66
  • 109
  • Thanks a lot for your reply - the parent property is null tho!? When I wrapped the stackpanel in a border control the parent property displayed border, but when I take that away so that the stackpanel is the 'root' control in the datatemplate it is null - so I'm assuming it can't access anything outside of the data template?? Thanks. –  Dec 19 '11 at 11:07
  • Then following Jon's approach would be the next way to go. – Adam Dec 19 '11 at 11:16
1
var listboxName = (stackpanel.Parent as ListBox).Name;
Ma7moud El-Naggar
  • 548
  • 1
  • 6
  • 18
  • Thanks a lot for your reply - the parent property is null tho!? When I wrapped the stackpanel in a border control the parent property displayed border, but when I take that away so that the stackpanel is the 'root' control in the datatemplate it is null - so I'm assuming it can't access anything outside of the data template?? Thanks. –  Dec 19 '11 at 11:08
1

According to this the StackPanel will not reach the root of the logical tree by the Parent property as it is located inside a template, so use the TemplatedParent property. In it you will probably get a ListBoxItem, which will have listbox as its parent.

XanderMK
  • 371
  • 1
  • 2
  • 13