在WPF窗口上动态添加多个按钮?

20

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

3个回答

36

我会将整个内容封装起来,通常情况下没有必要给按钮命名。像这样:

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上相关文章:

数据绑定概述
命令概述
数据模板概述


4
非常WPF风格的解决方案。我喜欢它 :) - Ben
1
你能否提供一个真实数据的例子吗?我对WPF非常陌生,这似乎有点超出我的能力范围。谢谢。 - RestingRobot
@Jlange:请阅读链接的文章,它们应该会给你所需的一切。 - H.B.
1
@sohaiby:对于有效使用框架来说,理解各种 WPF 概念至关重要,所以我很欣赏那些花时间去正确学习的人;这会让所有相关的人都更容易。 - H.B.
@Demodave:你只需要对它进行“添加”操作,例如。请注意,列表中项目属性的更改不会自动反映。要实现此类更新,项目类需要实现“INotifyPropertyChanged”。绑定是否有效?如果您没有相应地设置“DataContext”,则不会有效。 - H.B.
显示剩余4条评论

35

假设你有一个名为 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"));

希望这可以帮到你。


14

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接