我编写了动态创建按钮的代码,但是如何为每个按钮分配不同的功能?
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/