2015-05-25 150 views
0

任何想法如何我可以做一个点击事件创建另一个按钮不同的点击事件?创建一个提交按钮,当我按下添加,在一个按钮下的多个事件

我有一个使用EF的WPF应用程序。所以我被困在我需要按下按钮“添加”的部分,这将冻结其他按钮,然后创建另一个按钮“提交”,其中包含用于向表中添加数据的代码。我尝试了一些来自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!!"; 
} 

我甚至尝试了最明显的解决方案,以简单直接点击事件创建点击事件的另一个按钮。

+1

我不会动态创建的按钮,但立即操纵其知名度和或事实启用yes或no来代替经历了所有这些麻烦。 –

+1

为什么要创建一个新按钮,当您的xaml中的提交按钮带有visible = false并且只是在需要时将其可见性更改为true时? –

+0

什么是“根”变量? – Nazmul

回答

0

我会推荐一种替代方法,并立即将您的xml代码中的submitbutton,但它使它是无形的和禁用。

然后在事件处理程序中,您只需使其可见并启用它即可。

您的事件处理程序处理提交,按钮的动态创建,挂钩在窗体中等都可以避免,不必在运行时完成。

这将导致比原来的方法更好的可读代码和可维护代码,除非你有一个很好的理由。

+0

真棒,这解决了我的问题,没有任何不必要的复杂。我设置的可见性崩溃,使按钮不占用任何空间..谢谢:) –

-1

我做了以下编码,它是为我工作

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 !"); 
     }