我编写了可以动态创建按钮的代码,但是如何为每个按钮分配不同的功能呢?

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


现在每个按钮都显示“ Hello”,但我希望它是“ Hello1”,“ Hello2” .... ect。

最佳答案

如果可以使用DelegateCommands或RelayCommand属性和DisplayName属性创建对象的集合,则只需要将ItemsControl绑定到此Collection和一个DataTemplate即可将按钮绑定到Command和Text。

编辑:就在我脑海中

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


在您的视图模型中

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

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


在您的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:如果您需要一个新的动态按钮-只需向您的收藏添加一个新包装

07-28 02:37
查看更多