Question

If I have a class A which encapsulates a class B instance, is it possible to pass on through an instance of class A an event which was raised in class B? For example:

public classB
{
    ...
    public event EventArgs SomeEvent;
    protected virtual void OnSomeEvent(EventArgs e)
    ...
}

public classA
{
    ...
    private classB = new ClassB();
    ...
}

What I would like happen is for any instance of class A to also expose SomeEvent such that when it is raised by class B that it is raised by class A?

Please can someone offer assistance or suggestions?

Was it helpful?

Solution 2

Another option is to delegate the event to the original class:

public class ClassA
{
    private ClassB classB = new ClassB();
    public event EventHandler SomeEvent
    {
        add
        {
            classB.SomeEvent += value;
        }
        remove
        {
            classB.SomeEvent -= value;
        }
    }
}

That means when the event is raised in ClassB, all subscribers to ClassA.SomeEvent will also be notified because they are - in fact - subscribed to ClassB.SomeEvent. I'm not sure if that is going to be what you really want, but in any case, you can always use subscribe-and-raise method.

There's a catch here though: the sender object will be an instance of ClassB, not ClassA, which means that you can't delegate the event in, for example, WPF with INotifyDataErrorInfo validation, where the view model itself is expected to be raising the validation event. Then you just have to subscribe-and-raise.

OTHER TIPS

There is nothing like routed events for simple classes. You should subscribe to ClassB event and raise event from ClassA when classB raises event:

public class ClassA
{
    public event EventHandler SomeEvent = (s,e) => { };
    private ClassB classB = new ClassB();

    public ClassA()
    {
       classB.SomeEvent += (s,e) => SomeEvent(this, e);
    }    
}

More classic way:

public ClassA
{
    public event EventHandler SomeEvent;
    private ClassB classB = new ClassB();

    public ClassA()
    {
       classB.SomeEvent += ClassB_SomeEvent;
    }

    private void ClassB_SomeEvent(object sender, EventArgs e)
    {
        if (SomeEvent != null)
            SomeEvent(this, e);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top