【问题标题】:trigger object events from a itemsource从 itemssource 触发对象事件
【发布时间】:2019-01-21 12:52:48
【问题描述】:

我有一个对象,其中包含一个事件,一个静态函数 GetAll() 返回一个对象集合。

在我的 WPF 页面中,我填写了一个 ListBox 的 itemsource,认为这个函数是 GetAll。

现在我想实现 WPF 页面处理这个 ListBox 中每个对象的事件,但是我没有找到任何好的方法来做到这一点。

【问题讨论】:

    标签: c# wpf events collections


    【解决方案1】:

    使用foreach 循环遍历GetAll() 返回的集合,并将事件处理程序连接到其中的每个对象,例如:

    var collection = GetAll();
    if (collection != null)
    {
        foreach (var item in collection)
        {
            item.YourEvent += YourEventHandler;
        }
    }
    listBox.ItemsSource = collection;
    

    【讨论】:

    • 我不知道为什么有人认为它没有用。它有效。
    • 我一直在寻找不需要循环集合和绑定事件的东西。我有许多即时更改的系列。所以我希望事件直接来自对象。我想要达到的目标看起来很简单,但我认为这是不可能的。
    【解决方案2】:

    我猜你的课是这样的:

    public class Data
    {
       public static List<Data> GetAll(){.....};
       ...other property and in somewhere raise myEvent...
       public event doSomethingDelegate myEvent;
    }
    

    我的建议是尝试创建一个路由事件而不是普通事件。路由事件允许您在 ListBox 或 ListBox 的父级中侦听此事件。

    【讨论】:

    • 它看起来是一个很好的解决方案,但据我所知,它仅用于控件而不是类。我在网上找到的所有示例也给出了很多错误。我的类中的 C# 不接受此代码: public static readonly RoutedEvent ErrorChangeEvent = EventManager.RegisterRoutedEvent("ErrorChange", RoutingStartegy.Bubble, typeof(RoutedEventHandler), typeof(this));
    猜你喜欢
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多