Search code examples
c#wpfrouted-events

WPF: Custom routed event with extra information


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.


Solution

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