我是c#wpf的初学者,我试图让这段代码正常工作,试图搜索它,但我无法找到它......无论如何,这就是问题所在在我的代码中:
基本上我连接到存储我的方法名称的数据库:例如(window2_open) 然后在检索之后,我将在代码后面创建一个面板,并从数据集中添加方法名称:
// row[0].ToString() = window2_open
StackPanel panel = new StackPanel();
panel.AddHandler(StackPanel.MouseDownEvent, new MouseButtonEventHandler(row[0].ToString()));
但是我得到了一个错误"方法名称预期",所以我在谷歌查找并找到了这个:
MouseButtonEventHandler method = (MouseButtonEventHandler) this.GetType().GetMethod(row[0].ToString(), BindingFlags.NonPublic|BindingFlags.Instance).Invoke(this, new object[] {});
然后我得到参数不匹配的错误,我发现我需要传递与函数需要相同的参数,这是我的函数:
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
如何发送函数需要的相同参数?
答案 0 :(得分:1)
这样的事情应该有效:
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);
}));
当然,如果要点击,您必须将新StackPanel
添加到某个窗口。 (那是你在那里不寻常的建筑。)
(实际的鼠标处理程序是lambda;你不想在添加处理程序时调用处理程序。)
答案 1 :(得分:0)
请参阅以下链接: Calling a function from a string in C#
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);