2015-05-25 115 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 !"); 
     }