mercredi 15 juin 2022

Reflection added Delegate not firing

This is the code.

For example purposes, NewButton will have the name "Add", the SubMenuButtonNamesList is a list of strings containing the names of the buttons that I will be creating, afterwards I wanted to add the handler to these buttons based on the methods found in the mainwindow, matched by their names.

I think I did it properly since the button does have this handler added, but when I click the button nothing happens, it should show me a messagebox saying "yes".

public void Add_Method(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("Yes");
}
public MainWindow()
{
    InitializeComponent();

    //Create all sub-menu buttons
    foreach (var element in SubMenuButtonNamesList)
    {
        Button NewButton = new Button()
        {
            Background = new SolidColorBrush(new Color { A = 100, R = 231, G = 233, B = 245 }),
            FontFamily = new FontFamily("Century Gothic"),
            Content = element,
            FontSize = 14,
            Height = 30,
            Width = Double.NaN,
            VerticalAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Center
        };

        NewButton.Name = element.Trim();
        
        try
        {
            MethodInfo method = typeof(MainWindow).GetMethod(NewButton.Name + "_Method");
            Delegate myDelegate = Delegate.CreateDelegate(typeof(MouseButtonEventHandler), this, method);
            NewButton.MouseLeftButtonDown += (MouseButtonEventHandler)myDelegate;
        }
        catch (Exception e)
        {

        }

        SubMenuButtonsList.Add(NewButton);
    }

}




Aucun commentaire:

Enregistrer un commentaire