我已经将这个List分配给我的xaml中的itemscontrol,我想显示列表中每个项目的编号:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] assignments = new string[] { "https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Butterfly.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Dolphin.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Panda.png" };
Random rnd = new Random();
string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
string repeatNumber = "";
List<string> animals = new List<string>();
for (int i = 1; i < 100; i++)
{
if (i == 9)
{
repeatNumber = randomingArray[i % randomingArray.Length];
animals.Add(repeatNumber);
}
else if ((i % 9) == 0)
{
animals.Add(repeatNumber);
}
else
{
animals.Add(randomingArray[i % randomingArray.Length]);
}
ItemsControl1.ItemsSource = animals;
}
}
}
xaml的代码:
<ListBox x:Name="ItemsControl1" >
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="2" Width="Auto" Height="Auto">
<Image Source="{Binding}" Margin="0,0,5,0"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
基本上,应该有包含图片的方框,编号为1 - 99
我已尝试过List.count方法以及涉及xaml的其他内容,但是我无法让它工作。
答案 0 :(得分:2)
创建一个使用Number和Image源作为属性的类,并更新ItemTemplate。见下面的代码。
<ListBox x:Name="ItemsControl1" >
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="2" Width="Auto" Height="Auto">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Number}"/>
<Image Source="{Binding Source}" Margin="0,0,5,0"/>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] assignments = new string[] { "https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Butterfly.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Dolphin.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Panda.png" };
Random rnd = new Random();
string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
string repeatNumber = "";
List<ImageSource> animals = new List<ImageSource>();
for (int i = 1; i < 100; i++)
{
if (i == 9)
{
repeatNumber = randomingArray[i % randomingArray.Length];
animals.Add(new ImageSource(){ Source = repeatNumber, Number=i });
}
else if ((i % 9) == 0)
{
animals.Add(new ImageSource() { Source = repeatNumber, Number = i });
}
else
{
animals.Add(new ImageSource() { Source = randomingArray[i % randomingArray.Length], Number = i });
}
ItemsControl1.ItemsSource = animals;
}
}
}
class ImageSource
{
public int Number { get; set; }
public string Source { get; set; }
}