Instead of programmatically adding Image controls to a Canvas, write this XAML:
<ItemsControl x:Name="images">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="10"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Width="150" Height="150" Source="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Probably add some Margin
to the Image control in the DataTemplate.
In code behind, add one line to the constructor of your MainWindow:
using System.Linq;
...
public MainWindow()
{
InitializeComponent();
images.ItemsSource = Enumerable
.Range(1, 151)
.Select(i => string.Format("pack://application:,,,/Images/{0:000}.png", i));
}
Now you might want to create a proper view model, where you would have a collection-type property for your images, like
public class ViewModel
{
public ObservableCollection<string> Images { get; }
= new ObservableCollection<string>(Enumerable
.Range(1, 151)
.Select(i => string.Format("pack://application:,,,/Images/{0:000}.png", i)));
}
You would then assign the Window's DataContext to an instance of the view model, and bind to the collection property like this:
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
XAML
<ItemsControl ItemsSource="{Binding Images}">
...
</ItemsControl>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…