开发者

C# Event Passing/Bubble Up

开发者 https://www.devze.com 2022-12-19 04:08 出处:网络
I subscribe to an Event inside a class.Such as MainStation mainStation = StationFactory.GetMainStation();

I subscribe to an Event inside a class. Such as

MainStation mainStation = StationFactory.GetMainStation();  
mainStation.FrequencyChanged += new EventArgs(MainStation_FrequencyChanged);

My MainStation class raises the event on some condition by just calling the event FrequencyChanged()

The Problem

Now I have a scenario where I must instantiate SubStation from MainStation which is also a subclass of MainStation with some additional features and FrequencyChanged event must be subscribed as the MainStation subscrbed. Consider the code noted below:

public class MainStation
{
    public event EventHandler FrequencyChanged;
    public static SubStation CreateSubStation()
    {
        SubStation subStation = new SubStation();
        //here I want to pass/bubble FrequencyChanged event to SubStation
        subStation.FrequencyChanged = FrequencyChanged; //THIS IS WRONG
    }
}

Bottom Line

I want to fire an event that a class subscribes from another class, also bubble up events

Update

StationFactory creates MainStation and the FrequencyCh开发者_高级运维anged event in MainStation instance is set as defined in the first code block.


If FrequencyChanged does not belong to MainStation, but rather to some Base, you're going to have to chain and expose the event you're interested in.

public class MainStation : Base
{
    public event EventHandler StationFrequencyChanged;

    public MainStation()
    {
        // ...

        this.FrequencyChanged += new EventHandler(MainStation_FrequencyChanged);
    }

    void MainStation_FrequencyChanged(object sender, EventArgs e)
    {
        if (StationFrequencyChanged != null)
            StationFrequencyChanged(sender, e);
    }

    public void GetEventsFrom(MainStation src)
    {
        //this is where you assign src events to your object
        this.StationFrequencyChanged = src.StationFrequencyChanged;
    }

    public static SubStation CreateSubStation(MainStation main)
    {
        SubStation subStation = new SubStation();

        //register events    
        subStation.GetEventsFrom(main);

        return subStation;
    } 
}

public class SubStation : MainStation
{

} 


If you need something more flexible, it is possible to use WPF RoutedEvents.

Or implement similar approach manually: organize objects into tree and write an event manager that can route events upwards from tree node. If tree hierarchy fits your needs, it will be more convenient and predictable than forwarding every individual event in handler.


If your CreateSubStation method were not static, then the code you have would work as expected. (Provided that the event handlers on MainStation were setup before you created Substation...which isn't really a great design, IMO.)

0

精彩评论

暂无评论...
验证码 换一张
取 消