Multiple images from folder

前端 未结 3 861
深忆病人
深忆病人 2020-12-22 00:20

as I\'m fairly new to C# and WPF I just can\'t figure out how to do this. I have a form that should show 151 images (all pokemon generation 1 sprites) in a form. The way I\'

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-22 01:27

    Instead of programmatically adding Image controls to a Canvas, write this XAML:

    
        
            
                
            
        
        
            
                
            
        
    
    

    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 Images { get; }
            = new ObservableCollection(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

    
        ...
    
    

提交回复
热议问题