开发者

How to create an array of buttons in WPF?

开发者 https://www.devze.com 2022-12-23 07:02 出处:网络
I can create an array of butto开发者_如何学Gons in Windows Form but how can i do that in WPF(xaml) ?

I can create an array of butto开发者_如何学Gons in Windows Form but how can i do that in WPF(xaml) ? thanks in advance!


You can't do it directly in XAML (though you can do it in code, in exactly the same way as in Windows Forms). What you can do instead is use data binding and ItemsControl to create the buttons for you. You don't say what you need the control array for, but suppose you want a button for each Person in a collection:

Code behind

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

private void PersonButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
}

XAML

<ItemsControl ItemsSource="{Binding}" BorderThickness="0">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content="{Binding Name}"
              Click="PersonButton_Click"
              Margin="4"
              />
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

You can actually set up the whole thing in XAML using the ObjectDataProvider and CollectionViewSource, but this should be enough to get you started. And obviously the source can be something other than business data depending on what you need the "array" for.

0

精彩评论

暂无评论...
验证码 换一张
取 消