views:

191

answers:

1

I have a normal WPF window, let's call it TopLevel which has a bunch of controls in it, among other things a simple ListView which should log certain events in different elements in the application.

So suppose I have a Grid in TopLevel which contains a bunch of user controls called Task. Each Task has an object associated with them as a public property, let's call it Order, as well as a standard checkbox.

Now I want TopLevel to receive an event whenever the user checks a checkbox in a Task, but the event should contain the Order object as well, so I can work with it from TopLevel to put it into the event log.

How do I do that? I'm guessing I want to use routed events for it, but I can't figure out how to get the checkbox click to "find" Order to send it upwards to TopLevel.

A: 

How about something like this...

private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        CheckBox checkBox = sender as CheckBox;
        Task task = FindParentTask(checkBox);
        Order order = task.Order;
    }

Since you need to traverse up the visual tree to get to Task, you could try a bit of recursion...

public FrameworkElement FindParentTask(FrameworkElement element)
    {
        if (element.Parent.GetType() == typeof(Task))
            return element.Parent as FrameworkElement;
        else
            return FindParentTask(element.Parent as FrameworkElement);
    }

I've just tested this method to retrieve the parent Expander for a CheckBox on one of my UserControls, it's several levels up the visual tree, nested in a heap of StackPanels, Grids and DockPanels, worked a treat.

TabbyCool
So I can just convert a `DependencyObject` into whatever type I want like that?
Deniz Dogan
Are you referring to checkBox.Parent? If the underlying object is already of type Task, then yes, I think so. Do you have a sample of your code? Can't hurt to try it though, it's only a few lines :-)
TabbyCool
Also, the checkbox is not the immediate child of the `Task` so I would need to traverse upwards in some manner to get to the `Task`.
Deniz Dogan
It should still be achievable as you can access the Parent, then access the Parent of the Parent etc.
TabbyCool
That's where I get stuck at the moment, because how do I access the parent of a dependency object?
Deniz Dogan
Cast it to a FrameworkElement (or the actual type, if you know what the object is). Or see my edited answer, I need to check that this actually works though.
TabbyCool
I've edited my answer, I've tried this and it works perfectly. I used it to traverse up the tree from my CheckBox to get to the parent Expander, had to go through several levels of StackPanels, DockPanels and Grids to get there.
TabbyCool