Edward Tanguay
Edward Tanguay

Reputation: 193412

How can I pass addition parameters to my centralized event handlers?

In a WPF application, I've got my events centralized in one class like this:

public class EventFactory
{
    public static void Button_Edit_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("you clicked edit");
    }

    public static void Button_Add_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("you clicked add");
    }
}

so that I can reuse them in many Windows like this:

public Window1()
{
    InitializeComponent();

    ButtonEdit.Click += EventFactory.Button_Edit_Click;
    ButtonAdd.Click += EventFactory.Button_Add_Click;
}

This works fine, but now I want the events to act on the Windows which call them which I was able to do when the event handlers were simply in the code-behind for each window.

How can I e.g. inject a window object into the event handler so that that event handler can directly manipulate it, something like this:

ButtonEdit.Click += EventFactory.Button_Edit_Click(this);

Upvotes: 1

Views: 884

Answers (2)

Kent Boogaart
Kent Boogaart

Reputation: 178780

One way:

ButtonEdit.Click += EventFactory.ForConsumer<Window1>().Button_Edit_Click;

In other words, turn your factory class into an actual factory that creates objects based on some context. In this case, the context is the object consuming the events.

Another way:

public static void Button_Edit_Click(object sender, RoutedEventArgs e)
{
    Window window = Window.GetWindow(sender as DependencyObject);
    MessageBox.Show("you clicked edit");
}

I'm not particularly fond of either of these approaches, but there you go.

Upvotes: 2

Jo&#227;o Angelo
Jo&#227;o Angelo

Reputation: 57718

You can try something like this:

public class CommonEventHandler
{
    private CommonEventHandler() { }

    private object Context { get; set; }

    public static EventHandler CreateShowHandlerFor(object context)
    {
        CommonEventHandler handler = new CommonEventHandler();

        handler.Context = context;

        return new EventHandler(handler.HandleGenericShow);
    }

    private void HandleGenericShow(object sender, EventArgs e)
    {
        Console.WriteLine(this.Context);
    }
}

class Program
{
    static void Main(string[] args)
    {
        EventHandler show5 = CommonEventHandler.CreateShowHandlerFor(5);
        EventHandler show7 = CommonEventHandler.CreateShowHandlerFor(7);

        show5(null, EventArgs.Empty);
        Console.WriteLine("===");
        show7(null, EventArgs.Empty);
    }
}

You need to adapt the types to suit your needs but it shows the general idea.

Upvotes: 1

Related Questions