Reputation: 3529
I'm trying to figure out how to write the code (specifically an event handler) that contains an if statement whether the sender is contained in a GroupBox.
For example, lets say I have two GroupBoxes, and each contains a grid, and then that grid contains a textbox. I want to write a single event handler for "TextUpdated" that can differentiate between which groupbox the event is coming from (although this may sound overly complicated for only two TextBoxes, the situation I'm working on has many controls in each groupbox, but the event handler is the same).
Is there a way to make sender.IsContainedIn(GroupBoxOne) a bool? Because I have a grid in each groupbox, using GroupBox.Parent(xyz) doesn't seem to work because it picks up the grid as the parent instead.
Hopefully this makes sense... Thanks a lot.
Upvotes: 0
Views: 938
Reputation: 12884
Code:
// walk up the visual tree to find object of type T, starting from initial object
public static T FindUpVisualTree<T>(DependencyObject initial) where T : DependencyObject
{
DependencyObject current = initial;
while (current != null && current.GetType() != typeof(T))
{
current = VisualTreeHelper.GetParent(current);
}
return current as T;
}
Usage:
Grid gridContainingButton = FindUpVisualTree<Grid>(button01);
Upvotes: 0
Reputation: 3915
You can use VisualTreeHelper.GetParent to traverse the visual tree.
Here is a nice implementation on how to do it.
Upvotes: 5