动态添加多个按钮到wpf窗口?

时间:2011-05-08 19:20:57

标签: c# wpf button

如何在c#中向窗口添加多个按钮?这就是我需要做的...我从字典中获取多个用户值(在合理范围内,只有@ 5-6值)。对于每个值,我需要创建一个按钮。现在,我如何命名按钮,而不是按钮中的文字?我如何为每个按钮定义“点击”方法(它们都会有所不同)?如果我不再需要它,如何擦除按钮?

3 个答案:

答案 0 :(得分:29)

考虑一下名为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"));

希望这有帮助。

答案 1 :(得分:27)

我会封装整个事情,通常在命名按钮时没有意义。像这样:

public class SomeDataModel
{
    public string Content { get; set; }

    public ICommand Command { get; set; }

    public SomeDataModel(string content, ICommand command)
    {
        Content = content;
        Command = command;
    }
}

然后,您可以创建模型并将它们放入可绑定的集合中:

private readonly ObservableCollection<SomeDataModel> _MyData = new ObservableCollection<SomeDataModel>();
public ObservableCollection<SomeDataModel> MyData { get { return _MyData; } }

然后你只需要添加和删除项目并动态创建按钮:

<ItemsControl ItemsSource="{Binding MyData}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding Content}" Command="{Binding Command}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

有关详细信息,请参阅MSDN上的相关文章:

Data Binding Overview
Commanding Overview
Data Templating Overview

答案 2 :(得分:11)

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