【问题标题】:How do you create box for each element of array automatically in xaml?如何在 xaml 中自动为数组的每个元素创建框?
【发布时间】:2017-11-06 17:30:12
【问题描述】:

我一直在想——如何在 xaml 中自动为数组的每个元素创建框?假设我的代码有一个总共包含 99 个元素的数组,我希望每个元素都包含这个 50px*50px 的小盒子。当然我不认为正确的方法是创建 99 个额外的小盒子并将它们分配给数组。

到目前为止,我已经研究了数据绑定和 ItemsControl,但找不到足够好的示例供我学习。

 string[] assignments = new string[] { "A", "B", "C", "D", "E", "F" };
 Random rnd = new Random();
 string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();

 string repeatNumber = "";

 for (int i = 1; i < 100; i++)
 {
      if (i == 9)
      {
         repeatNumber = randomingArray[i % randomingArray.Length];
         Console.WriteLine(repeatNumber);

      }
      else if ((i % 9) == 0)
      {
         Console.WriteLine(repeatNumber);
      }
      else
      {
         Console.WriteLine(randomingArray[i % randomingArray.Length]);
      }

 }

我该怎么做?

【问题讨论】:

  • 您在 ItemsControl 的 ItemTemplate 中定义“小盒子”,并将 ItemsControl 的 ItemsSource 属性绑定到返回包含 99 个元素的数组的视图模型的属性。

标签: c# .net arrays wpf xaml


【解决方案1】:

我会说尝试更多基本的 WPF 教程。我也建议查看一些 MVVM 教程。现在看下面的代码。

<Grid>       
    <ListBox x:Name="ItemsControl1" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Aqua" BorderThickness="2" Width="Auto" Height="Auto" >
                    <TextBlock Text="{Binding}" Margin="10"/>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ItemsControl1.ItemsSource = new string[] { "A", "B", "C", "D" };
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-06
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多