[英]Dynamically add multiple buttons to wpf window?
我如何将多个按钮添加到 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"));
希望这有帮助。
Xml代码:
<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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.