0
votes

Is there any way to set a button click routed event handler from a class static method?

I have got UserControl item "SendButton" with a button in XAML and two arguments:

public SendButton(string buttonText, string eventHandler)
        {
            InitializeComponent();
            ButtonBlock.Content = buttonText;

            // This is what I´ve tried
            ButtonBlock.Click += (Func<RoutedEventHandler>) typeof(RoutedEvents).GetMethod(eventHandler);

            // This is what I want to achieve:
            // ButtonBlock.Click += RoutedEvents.WhatIsYourName();
            // But it doesn´t work anyways, because of a missing arguments
        }

And then static method inside the class

public class RoutedEvents
    {
        public static void WhatIsYourName(object sender, TextChangedEventArgs e)
        {
            // 
        }
    }

And this is how I would like to call it:

new SendButton("Send", "WhatIsYourName");  

Thank you

1

1 Answers

3
votes

The UserControl's constructor should take a RoutedEventHandler as argument:

public SendButton(string buttonText, RoutedEventHandler clickHandler)
{
    InitializeComponent();

    ButtonBlock.Content = buttonText;
    ButtonBlock.Click += clickHandler;
}

A handler method passed as argument must have the correct signature, with a RoutedEventArgs as second parameter:

public class RoutedEvents
{
    public static void WhatIsYourName(object sender, RoutedEventArgs e)
    {
        // 
    }
}

Then pass it like this (without parentheses):

new SendButton("Send", RoutedEvents.WhatIsYourName);