Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise/fire your own Event? (like an UIButton)

Tags:

xamarin.ios

I find a lot of resources on how to react on an Event (or delegate). For example:

Control.ValueChanged += (sender, e) =>
        {
            //do something
        };

However, I don't find how I can create my own Event? Basically I have a class that needs to 'fire' an event and in the class that creates this object you can react on this Event.

Any idea?

If I would do it with a Delegate instead, how should I do that (creating my own Delegate object that can be implemented by another class)?

Thanks!

like image 805
Matt Avatar asked Dec 27 '22 09:12

Matt


2 Answers

You mean something like this?

class Foo
{
    public event EventHandler MyEvent;

    public void DoSomething()
    {
        // do stuff

        // raise the MyEvent event
        var handler = MyEvent;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}
like image 79
ctacke Avatar answered Jan 29 '23 09:01

ctacke


I personally use Actions.

public abstract class ServiceClient
{
    public Action OnNetworkActivityStarted { get; set; }

    private void StartNetworkActivity()
    {
        if (OnNetworkActivityStarted != null)
            OnNetworkActivityStarted();
    }
}

Any inheriting class would/could use the logic you have provided above.

public class MyClient : ServiceClient
{
    public MyClient()
    {
        this.OnNetworkActivityStarted += () => 
        {
            //do whatever the subclass needs to do when the event is fired
        };    
    }
}

I have this implemented in class-library I plan on using for cross-platform mobile apps. This allows each device to implement their own strategy for letting the user know that network has started.

I hope this helps.

like image 20
valdetero Avatar answered Jan 29 '23 09:01

valdetero