user1017882
user1017882

Reputation:

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.

Upvotes: 0

Views: 243

Answers (4)

XanderMK
XanderMK

Reputation: 389

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.

Upvotes: 1

Jon
Jon

Reputation: 437664

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

Upvotes: 2

Ma7moud El-Naggar
Ma7moud El-Naggar

Reputation: 558

var listboxName = (stackpanel.Parent as ListBox).Name;

Upvotes: 1

Adam
Adam

Reputation: 16199

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

Upvotes: 1

Related Questions