这是代码。
例如,NewButton将具有名称" add " SubMenuButtonNamesList是包含我将创建的按钮名称的字符串列表,然后我想根据在主窗口中找到的方法为这些按钮添加处理程序,并与它们的名称相匹配。
我认为我做得很好,因为按钮确实添加了这个处理程序,但是当我单击按钮时什么都没有发生,它应该向我显示一个消息框,说"是"
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);
}
}
出现了Button的MouseLeftButtonDown事件(没有检查其他任何东西),如果以这种方式添加将不会触发,但是如果你为Click事件这样做,它将正确触发,参见下面的修改片段:
MethodInfo method = typeof(MainWindow).GetMethod(NewButton.Name + "_Method");
Delegate myDelegate = Delegate.CreateDelegate(typeof(RoutedEventHandler), this, method);
NewButton.Click += (RoutedEventHandler)myDelegate;
方法:
public void Add_Method(object sender, RoutedEventArgs e)
{
MessageBox.Show("Yes");
}