2013-10-22 86 views
1

我製作了動態創建按鈕的代碼,但是如何爲每個按鈕分配不同的功能?在WPF中添加動態按鈕

for (int i = 0; i < Buttons.Count; i++) 
{ 
      Button newBtn = new Button(); 
      newBtn.Content = Buttons[i]; 
      newBtn.Name = "Button" + i.ToString(); 
      newBtn.Height = 23; 
      stackPanel1.Children.Add(newBtn); 
      newBtn.Click += new RoutedEventHandler(newBtn_Click); 
} 

private void newBtn_Click(object sender, RoutedEventArgs e) 
{ 
     MessageBox.Show("Hello"); 
} 

現在每個按鈕顯示「你好」,但我希望它是「Hello1」,「Hello2」 ......等。

+2

我強烈建議您閱讀'ItemsControl'。這不是在WPF中動態生成用戶界面的方式。 –

回答

5

如果您可以使用DelegateCommands或RelayCommand屬性和DisplayName屬性創建一個對象集合 - 您只需要將一個ItemsControl綁定到此Collection並將DataTemplate綁定到Command和Text按鈕。

編輯:只需在您的視圖模型

public ObservableCollection<MyCommandWrapper> MyCommands {get;set;} 

MyCommands.Add(new MyCommandWrapper(){Command = MyTestCommand1, DisplayName = "Test 1"}; 
... 

我的頭

public class MyCommandWrapper 
{ 
    public ICommand Command {get;set;} 
    public string DisplayName {get;set;} 
} 

在你的XAML

<ItemsControl ItemsSource="{Binding MyCommands}"> 
    <ItemsControl.Resources> 
    <DataTemplate DataType="{x:Type local:MyCommandWrapper}"> 
     <Button Content="{Binding DisplayName}" Command="{Binding Command}"/> 
    </DataTemplate> 
    </ItemsControl.Resources> 
    </ItemsControl> 

編輯2:如果你需要一個新的動態按鈕 - 只添加一個新的包裝到您的收藏

1
private void newBtn_Click(object sender, RoutedEventArgs e) 
{ 
     var button = sender as Button; 
     var buttonNumber = button.Name.Remove(0, 6); 

     MessageBox.Show("Hello" + buttonNumber); 
} 
1

檢查您​​功能的sender參數。它應該包含被點擊的按鈕的實例。你可以將它轉換爲一個按鈕,檢查名稱:

private void newBtn_Click(object sender, RoutedEventArgs e) 
{ 
    var btn = sender as Button; 
    if(btn != null) 
    { 
     MessageBox.Show(btn.Name); 
    } 
} 

如果你不想檢查Name屬性,你還可以使用標記屬性(http://msdn.microsoft.com/library/system.windows.frameworkelement.tag.aspx),以您可以指定任意對象,後來檢查:

Button newBtn = new Button(); 
newBtn.Tag = i; 
單擊處理程序

及更高版本:

private void newBtn_Click(object sender, RoutedEventArgs e) 
{ 
    var btn = sender as Button; 
    if(btn != null) 
    { 
     if(btn.Tag is int) 
      MessageBox.Show(String.Format("Hello{0}", btn.Tag)); 
    } 
} 

我寧願與標籤解決方案,因爲它比從一個字符串中提取更多的東西是安全的。

1
newBtn.Click += new RoutedEventHandler((s,e) => MessageBox.Show("hallo"+((Button)s).Name); 
2
for (int i = 0; i < Buttons.Count; i++) 
    { 
       Button newBtn = new Button(); 
       newBtn.Content = Buttons[i]; 
       newBtn.Height = 23; 
       newBtn.Tag=i; 
       stackPanel1.Children.Add(newBtn); 
       newBtn.Click += new RoutedEventHandler(newBtn_Click); 
    } 

private void newBtn_Click(object sender, RoutedEventArgs e) 
{ 
     Button btn=sender as Button; 
     int i=(int)btn.Tag; 

     switch(i) 
     { 
     case 0: /*do something*/ break; 
     case 1: /*do something else*/ break; 
     default: /*do something by default*/ break; 
     } 
}