c# - 在 WPF 中添加动态按钮

标签 c# 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");
}

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

最佳答案

如果您可以使用 DelegateCommands 或 RelayCommand 属性和 DisplayName 属性创建一个对象集合 - 您只需要一个 ItemsControl 绑定(bind)到这个集合和一个 DataTemplate 来绑定(bind)一个按钮到命令和文本。

编辑:就在我的脑海里

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

在你的 View 模型中

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

关于c# - 在 WPF 中添加动态按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19517292/

相关文章:

wpf - 不能将样式建立在另一种样式的基础上

c# - 消耗CPU使用率的进程

c# - 尽管我没有回滚我的事务,但 SQLite 事务没有成功?

c# - 信号R "Error during start request. Stopping the connection."

wpf - 在 xaml 中设置自定义窗口属性

c# - 当您必须直接引用控件时,MVVM 如何适应 WPF

c# - 将 nhibernate 与 Unity3D 集成

c# - 如何确定 C# 编译器的路径?

c# - 对 WPF 事件触发器进行保护。这可能吗?

c# - Gridsplitter 在 MouseOver 上可见