如何在 WPF 中创建一组按钮? [英] How to create an array of buttons in WPF?

查看:76
本文介绍了如何在 WPF 中创建一组按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 Windows 窗体中创建一组按钮,但如何在 WPF(xaml) 中创建?提前致谢!

I can create an array of buttons in Windows Form but how can i do that in WPF(xaml) ? thanks in advance!

推荐答案

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

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

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

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

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.

这篇关于如何在 WPF 中创建一组按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆