Reputation: 95
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?
Upvotes: 2
Views: 1311
Reputation: 5498
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.)
Upvotes: 1
Reputation: 2875
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);
Upvotes: 0