我想了解如何将从类中引发的事件转发到实现List<>的所有者类。提升事件的类包含在。主类称为PCCControls
并包含List<ControlBox>
个对象。每个ControlBox
都会实现一个名为ButtonPushed
的事件。
我希望通过在ControlBox
类中实现类似于以下内容的事件,将事件从PCCControls
类移动到PCCControls
类。
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());
}
}
因此,基于上面的代码,我想将事件ButtonPushed
从ControlBox
类移到PCCControls
类,然后只传递ControlBox
事件被触发为ButtonPushed
事件的参数。
这是如何实现的?非常感谢您的支持
答案 0 :(得分:0)
你所要求的并不是很清楚;但是,我会捅一下。您只需获取PCCControls
课程即可订阅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:
}
}
如果这不是您要找的,请提供更多详细信息。
答案 1 :(得分:0)
如果确保实际列表对PCCControls类保持私有(因此客户端代码无法直接向/从中添加/删除ControlBox),您可以在添加或删除项目时订阅/取消订阅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());
}
}