2

I'm a beginner in c# wpf and I'm trying to get this code to work, tried to search it but I can't find it.., anyway here's the problem in my code:

Basically im connecting to a database that stores my method names: e.g (window2_open) then after retrieving it, I will create a panel in code behind and add the method name from the dataset:

// row[0].ToString() = window2_open
StackPanel panel = new StackPanel();
panel.AddHandler(StackPanel.MouseDownEvent, new MouseButtonEventHandler(row[0].ToString()));

but i got an error "method name expected", so I looked it up in google and found this:

MouseButtonEventHandler method = (MouseButtonEventHandler) this.GetType().GetMethod(row[0].ToString(), BindingFlags.NonPublic|BindingFlags.Instance).Invoke(this, new object[] {});

but then i get parameter mismatched error, I found that I need to pass the same argument as the function needs, this is my function:

private void window2_open(object sender, RoutedEventArgs e)
{
    window2 win2 = new window2();
    win2.ShowInTaskbar = false;
    win2.Owner = this;
    win2.ShowDialog();
}
// where window2 is another xaml

how can I send the same parameter that the function need?

Gen
  • 95
  • 1
  • 10
  • Do you want to add a handler to the stackpanel or do you want to add content to the stackpanel ? – Nawed Nabi Zada Jan 22 '16 at 13:29
  • I'm trying to add handler to a stackpanel, it works if I type the method name directly but I want to store it to a database and retrieve it dynamically. – Gen Jan 22 '16 at 13:49

2 Answers2

1

Something like this should work:

string methodName = nameof(window2_open); // Assume this came from the DB
panel.AddHandler(MouseDownEvent, new MouseButtonEventHandler((sender, args) =>
    {
        MethodInfo methodInfo = GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);

        // The arguments array must match the argument types of the method you're calling
        object[] arguments = { panel, args };
        methodInfo.Invoke(this, arguments);
    }));

Of course, you have to add your new StackPanel to some window if it is to be clickable. (That's an unusual architecture you have there.)

(The actual mouse handler is the lambda; you don't want to invoke the handler while adding it.)

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
  • Thanks man I'll try this out later when I get home, anyway do you think my architecture is unusual? I'm actually a beginner and I'm trying to do everything from xaml and code behind :D – Gen Jan 23 '16 at 01:12
  • It worked man, though I had to add if(methodInfo != null){} before invoking cause there was an error "Object reference not set to an instance of an object", thanks. – Gen Jan 23 '16 at 13:22
0

See the link below: Calling a function from a string in C#

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
Community
  • 1
  • 1
Nawed Nabi Zada
  • 2,819
  • 5
  • 29
  • 40