当我按Add时创建一个提交按钮,一个按钮下有多个事件
本文关键字:一个 按钮 事件 提交 Add 创建 | 更新日期: 2023-09-27 17:50:44
我怎么能让一个点击事件创建另一个按钮与不同的点击事件?
我有一个WPF应用程序使用EF。所以我被困在部分,我需要按下按钮"添加",这将冻结其他按钮,然后创建另一个按钮"提交"与代码添加数据到表。我已经尝试了msdn的一些建议,但它不起作用。下面是代码(之前在XAML中添加了一个名为b1的按钮):
public partial class RoutedEventAddRemoveHandler {
void MakeButton(object sender, RoutedEventArgs e)
{
Button b2 = new Button();
b2.Content = "New Button";
// Associate event handler to the button. You can remove the event
// handler using "-=" syntax rather than "+=".
b2.Click += new RoutedEventHandler(Onb2Click);
root.Children.Insert(root.Children.Count, b2);
DockPanel.SetDock(b2, Dock.Top);
text1.Text = "Now click the second button...";
b1.IsEnabled = false;
}
void Onb2Click(object sender, RoutedEventArgs e)
{
text1.Text = "New Button (b2) Was Clicked!!";
}
我甚至尝试了最明显的解决方案,即直接在click event中创建另一个带有click event的按钮
我建议您使用另一种方法,将提交按钮放在您的xaml代码中,但要使其不可见且禁用。
那么在事件处理程序中,你只需要使它可见并启用它。
处理提交的事件处理程序,按钮的动态创建,将其与表单挂钩等等都可以避免,并且不必在运行时完成。
这将产生比原始方法更好的可读代码和可维护代码,除非你有一个很好的理由。
我已经完成了以下编码,它正在为我工作
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Button oButton = new Button();
oButton.Name = "btnMessage";
oButton.Content = "Message Show";
oButton.Height = 50;
oButton.Width = 50;
oButton.Click += new RoutedEventHandler(oButton_Click);
//root is a stack panel
root.Children.Insert(root.Children.Count, oButton);
DockPanel.SetDock(oButton, Dock.Top);
}
void oButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello World !");
}