如何在WPF中创建按钮数组?

Way*_*yne 7 wpf xaml

我可以在Windows窗体中创建一个按钮数组,但是如何在WPF(xaml)中执行此操作?提前致谢!

ito*_*son 17

您不能直接在XAML中执行此操作(尽管您可以在代码中执行此操作,与Windows窗体中的方式完全相同).你可以做的是使用数据绑定和ItemsControl来为你创建按钮.你没有说出你需要控制数组的内容,但是假设你想要一个集合中每个Person的按钮:

// Code behind
public Window1()
{
  var people = new ObservableCollection<Person>();
  // Populate people
  DataContext = people;
}

// XAML
<ItemsControl ItemsSource="{Binding}" BorderThickness="0">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content="{Binding Name}"
              Click="PersonButton_Click"
              Margin="4"
              />
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

实际上,您可以使用ObjectDataProvider和CollectionViewSource在XAML中设置整个内容,但这应该足以让您入门.显然,源代码可以是业务数据以外的东西,具体取决于您需要的"数组".