我如何在C#中向窗口添加多个按钮? 我需要做的是...我正在从字典中获取多个用户值(在合理范围内,仅@ 5-6个值)。对于每个值,我都需要创建一个按钮。现在,我如何命名该按钮而不是按钮内部的文本?我如何为每个按钮定义“单击”方法(它们都会不同)? 如果我不想要该按钮,我该如何擦除它?
我会将整个内容封装起来,通常情况下没有必要给按钮命名。像这样:
public class SomeDataModel
{
public string Content { get; }
public ICommand Command { get; }
public SomeDataModel(string content, ICommand command)
{
Content = content;
Command = command;
}
}
然后您可以创建模型并将其放入可绑定集合中:
public ObservableCollection<SomeDataModel> MyData { get; } =
new ObservableCollection<SomeDataModel>();
然后你只需要向其中添加和删除项,并动态创建按钮:
<ItemsControl ItemsSource="{Binding MyData}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Content}" Command="{Binding Command}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
更多信息请参见MSDN上相关文章:
假设你有一个名为 sp 的 StackPanel
for(int i=0; i<5; i++)
{
System.Windows.Controls.Button newBtn = new Button();
newBtn.Content = i.ToString();
newBtn.Name = "Button" + i.ToString();
sp.Children.Add(newBtn);
}
要删除按钮,你可以这样做:
sp.Children.Remove((UIElement)this.FindName("Button0"));
希望这可以帮到你。
Xaml 代码:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<UniformGrid x:Name="grid">
</UniformGrid>
</Window>
代码后台:
public MainWindow()
{
InitializeComponent();
for (int i = 0; i < 10; ++i)
{
Button button = new Button()
{
Content = string.Format("Button for {0}", i),
Tag = i
};
button.Click += new RoutedEventHandler(button_Click);
this.grid.Children.Add(button);
}
}
void button_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine(string.Format("You clicked on the {0}. button.", (sender as Button).Tag));
}