PassingParametersInEvent - lucyberryhub/WPF.Tutorial GitHub Wiki

🍒 Lesson 2: Sending Messages Between Berry Pickers! (Passing Parameters in an Event)

Imagine you are working on a berry farm 🌱, and you need to send a message to another berry picker to let them know how many strawberries you picked. You need a way to pass information from one worker to another.

🍓 How Do We Send a Message?

We need to create a special message card (event data) that includes:

  • A message (e.g., "Strawberries picked! 🍓")
  • The number of berries picked

🍓 Step 1: Create the Message Card (Custom Event Data)

We create a special BerryEvent that holds our message:

public class BerryEvent : EventArgs
{
    public string Message { get; }
    public int BerryCount { get; }

    public BerryEvent(string message, int berryCount)
    {
        Message = message;
        BerryCount = berryCount;
    }
}

Now, we have a way to store important berry-related information!


🍓 Step 2: Announce the Berry Count (Declare the Event)

Just like how farmers shout out updates to the team, we need a way to announce when berries have been picked! 🎤

public event EventHandler<BerryEvent> BerryPicked;

Now, whenever berries are picked, we can send this message to other pickers.


🍓 Step 3: Send the Message (Invoke the Event)

When someone picks berries, we send the update:

BerryPicked?.Invoke(this, new BerryEvent("Strawberries picked! 🍓", 42));

This means:
Tell all berry pickers that strawberries were picked.
Send the number of strawberries (42) along with the message.


🍓 Step 4: Receiving the Message (Subscribe to the Event)

Now, another berry picker listens for the update and takes action:

private void OnBerryPicked(object sender, BerryEvent e)
{
    Console.WriteLine($"{e.Message} Total berries: {e.BerryCount}");
}

// Subscribe to the berry announcements!
farm.BerryPicked += OnBerryPicked;

Now, whenever berries are picked, all pickers will hear the update! 📢


🍓 Final Summary

✅ We created a BerryEvent to hold messages.
✅ We announced when berries were picked.
✅ Other berry pickers received the message and took action!

Just like that, our berry farm runs smoothly with clear communication! 🚜

⚠️ **GitHub.com Fallback** ⚠️