2011-02-24 99 views
12

我有一個在運行時動態生成的按鈕數組。我有我的代碼中按鈕單擊的功能,但我找不到在代碼中設置按鈕的單擊名稱的方法。所以,在C#代碼中點擊WPF按鈕

什麼是代碼等效XAML:

<Button x:Name="btn1" Click="btn1_Click">

或者,我應該怎麼地方 「????」在下面的代碼:

Button btn = new Button()
btn.Name = "btn1";
btn.???? = "btn1_Click";

回答

31
Button btn = new Button(); 
btn.Name = "btn1"; 
btn.Click += btn1_Click; 

private void btn1_Click(object sender, RoutedEventArgs e) 
{ 
    // do something 
} 
9

下應該做的伎倆:

btn.Click += btn1_Click; 
3
// sample C# 
public void populateButtons() 
{ 
    int xPos; 
    int yPos; 

    Random ranNum = new Random(); 

    for (int i = 0; i < 50; i++) 
    { 
     Button foo = new Button(); 
     Style buttonStyle = Window.Resources["CurvedButton"] as Style; 

     int sizeValue = ranNum.Next(50); 

     foo.Width = sizeValue; 
     foo.Height = sizeValue; 
     foo.Name = "button" + i; 

     xPos = ranNum.Next(300); 
     yPos = ranNum.Next(200); 

     foo.HorizontalAlignment = HorizontalAlignment.Left; 
     foo.VerticalAlignment = VerticalAlignment.Top; 
     foo.Margin = new Thickness(xPos, yPos, 0, 0); 

     foo.Style = buttonStyle; 

     foo.Click += new RoutedEventHandler(buttonClick); 
     LayoutRoot.Children.Add(foo); 
    } 
} 

private void buttonClick(object sender, EventArgs e) 
{ 
    //do something or... 
    Button clicked = (Button) sender; 
    MessageBox.Show("Button's name is: " + clicked.Name); 
} 
1

我不認爲WPF支持什麼你正試圖實現ie 。使用方法名稱或btn1.Click =「btn1_Click」將按鈕分配給按鈕。您必須使用上述答案中建議的方法,即使用適當的方法註冊按鈕點擊事件 btn1.Click + = btn1_Click;

0

您應該放置在線下方

btn.Click = btn.Click + btn1_Click;