How to bind to a list of images

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

I have changed my code to this:

the view:


            
                

        
相关标签:
2条回答
  • 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.

    <ItemsControl ItemsSource="{Binding Images}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    or

    <ListBox ItemsSource="{Binding Images}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    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<string>.

    public class Gal
    {
        public ObservableCollection<string> Images { get; set; }
    }
    

    You may create an instance of that class like so:

    var gallery = new Gal();
    gallery.Images = new ObservableCollection<string>(
        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;
    
    0 讨论(0)
  • 2020-12-07 06:00

    so I basically created a loaded event on the listbox and added this code

      private void list_of_images_Loaded_1(object sender, RoutedEventArgs e)
        {
            ListBox lst = (ListBox)sender;
            lst.ItemsSource = new_Classifieds_list[0].ImageUrls;
        }
    

    which binds the itemssource of the listbox to the list of imageurls. since I cannot access the listbox from codebehind due to it being inside the panorama's itemstemplate

    0 讨论(0)
提交回复
热议问题