WPF:带有额外信息的自定义路由事件

发布于 2024-08-18 23:41:45 字数 528 浏览 8 评论 0原文

我有一个普通的 WPF 窗口,我们称其为 TopLevel,其中包含一堆控件,其中还有一个简单的 ListView,它应该在窗口中的不同元素中记录某些事件。应用。

因此,假设我在 TopLevel 中有一个 Grid,其中包含一堆名为 Task 的用户控件。每个Task都有一个与它们关联的对象作为公共属性,我们称之为Order,以及一个标准复选框。

现在,我希望每当用户选中 Task 中的复选框时 TopLevel 都会收到一个事件,但该事件还应该包含 Order 对象,所以我可以从 TopLevel 使用它,将其放入事件日志中。

我该怎么做?我猜我想为其使用路由事件,但我不知道如何让复选框单击“查找”Order 将其向上发送到 TopLevel

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼性发作 2024-08-25 23:41:45

像这样的事情怎么样...

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

由于您需要遍历可视化树才能到达任务,因此您可以尝试一些递归...

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

我刚刚测试了此方法来检索其中一个复选框的父级 Expander我的 UserControls,它在视觉树上有好几层,嵌套在一堆 StackPanels、Grids 和 DockPanels 中,非常有用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文