0

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 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.