How to bind to a list of images

前端 未结 2 673
名媛妹妹
名媛妹妹 2020-12-07 05:35

I have changed my code to this:

the view:


            
                

        
2条回答
  •  Happy的楠姐
    2020-12-07 05:51

    Depending on whether you want to just display a list of images or if you also want to be able to select them, you may either choose an ItemsControl or a ListBox. In both case you have to define a DataTemplate that controls how each item is displayed.

    
        
            
                
            
        
    
    

    or

    
        
            
                
            
        
    
    

    Then you should think about how you define your item class. Just in case you want to be able to dynamically add or remove images from the list and let the UI be automatically updated, you should use an ObservableCollection as container type. As there is a built-in type conversion from string to ImageSource (the type of the Image control's Source property), you may simply use an ObservableCollection.

    public class Gal
    {
        public ObservableCollection Images { get; set; }
    }
    

    You may create an instance of that class like so:

    var gallery = new Gal();
    gallery.Images = new ObservableCollection(
        Directory.EnumerateFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg"));
    

    Now you may directly bind to that instance by simply setting the DataContext of your Window (or wherever the image list should be shown) to this instance:

    DataContext = gallery;
    

    Note the binding declaration in the ItemsControl or ListBox above was {Binding Images}. If you really have to have a property Gallery (which I assume is in MainWindow) and bind like {Binding Gallery.Images} you may set the DataContext like this:

    DataContext = this;
    

提交回复
热议问题