0

我想了解如何将从类引发的事件转发到实现 List<> 的所有者类,引发事件的类包含在其中。主类被调用PCCControls并包含一个List<ControlBox>对象。每个都ControlBox实现了一个名为 的事件ButtonPushed

我想通过在类中实现类似于以下内容的事件将事件从ControlBox类移动到类:PCCControlsPCCControls

public delegate ControlBoxButtonPushedHandler(object sender, ControlBox controlbox);
public event ControlBoxButtonPushedHandler ButtonPushed;

我有以下内容:

public class PCCControls
{
    List<ControlBox> ControlBoxes;
}  

public class ControlBox
{
    public event ButtonPushed;  

    public ProcessSub()
    {
        if(ButtonPushed != null) ButtonPushed(this, new EventArgs());
    }
}

因此,基于上面的代码,我想将事件ButtonPushedControlBox类移动到PCCControls类,并将ControlBox触发事件的事件作为参数传递给ButtonPushed事件。

这是如何实现的?您的支持将不胜感激

4

2 回答 2

0

你问的不是很清楚;但是,我会试一试。您可以简单地让PCCControls类订阅 a 中的事件ControlBox

public class PCCControls
{
    List<ControlBox> ControlBoxes;
// initialization of ControlBoxes done elsewhere...
    public voice SomeMethod()
    {
        ControlBoxes.ElementAt(0).ButtonPushed += controlBox_ButtonPushed;
    }
    public void controlBox_ButtonPushed(object sender, EventArgs e)
    {
        // TODO:
    }
}

如果这不是您要找的,请提供更多详细信息。

于 2012-05-27T20:53:06.673 回答
0

如果您确保实际列表对 PCCControls 类保持私有(因此客户端代码不能直接向其中添加/删除 ControlBoxes),您可以在添加或删除项目时订阅/取消订阅 ControlBox 的 ButtonPushed 事件,然后定义您自己的事件以将其转发给客户端代码。像这样的东西:

public class PCCControls
{
    public event EventHandler<PCCButtonPushedEventArgs> PCCButtonPushed;

    List<ControlBox> ControlBoxes;

    public void AddControlBox(ControlBox box) 
    {
        box.ButtonPushed += OnButtonPushed;
        ControlBoxes.Add(box);
    }
    public void RemoveControlBox(ControlBox box) 
    {
        box.ButtonPushed -= OnButtonPushed;
        ControlBoxes.Remove(box);
    }
    private void OnButtonPushed(object sender, EventArgs e)
    {
        var handler = PCCButtonPushed;
        if (handler != null) 
        {
           var box = (ControlBox)sender;
           handler(this, new PCCButtonPushedEventArgs(box));
        }
    }
}  

public class ControlBox
{
    public event ButtonPushed;  
    public ProcessSub()
    {
        if(ButtonPushed != null) ButtonPushed(this, new EventArgs());
    }
}
于 2012-05-27T20:57:09.250 回答