The task is that when selecting item (the item is an image) from the listbox, the selected image is displayed in the image control.

For a start, I received a list of subfolders in which images are stored, this list is listed in the combobox

DirectoryInfo fillComboBox = new DirectoryInfo(path); var x = fillComboBox.GetDirectories(); foreach (var s in x) { cb1.Items.Add(s); } 

Then, choosing one of the received folders in the combobox, I fill the Listbox with the contents of this folder (image names),

  if(cb1.SelectedItem.ToString() == namefolder) { var dir = new DirectoryInfo(path + @"\Image"); var files = dir.GetFiles("*.*"); lb1.ItemsSource = files; lb1.DisplayMemberPath = "Name"; } 

after that, when you click on item in the listbox, the selected picture should be displayed in image. At this point, there were problems, with collections of this type I do not quite understand how to work.

For example, if I do this way using ObservableCollection, I create a class in it with two fields and a constructor with two fields.

 class CollectImg { public string path; public ImageSource resource; public CollectImg(string path, ImageSource resource) { this.path = path; this.resource = resource; } } 

then I define the collection

  ObservableCollection<CollectImg> collect = new ObservableCollection<CollectImg> { }; 

    1 answer 1

    You are doing wrong. Take advantage of MVVM.

    1. Get a VM object describing a picture like this:

       class SingleImageVM { public string Name { get; } public ImageSource Image { get; } public SingleImageVM(string path) { Name = Path.GetFileName(path); Image = BitmapFrame.Create(new Uri(path)); } } 
    2. Get a collection of such SingleImageVM in your VM (let it be in a property called Images ).

    3. Your combobox should look something like this:

       <ComboBox ItemsSource="{Binding Images}" SelectedItem="{Binding SelectedImage}" DisplayMemberPath="Name"/> 

      Remember to put the SelectedImage property of type SingleImageVM in your VM and implement INotifyPropertyChanged

    4. Now you can attach a picture:

       <Image Source="{Binding SelectedImage.Image}"/> 

    Everything!

    • And if you do a little differently using ObservableCollection, the collections give the type of class that they created. How then in the body to describe the path and resource? (added to the question the essence of what I want) - test19
    • Just the entire collection of images through the resource field must also be output to the listbox - test19
    • @SOFL: Well yes, ObservableCollection<SingleImageVM> - VladD
    • That is, ObservableCollection <CollectImg> collect = new ObservableCollection <CollectImg> and all? Nothing needs to be added to the body, for example, if the collection type is a string, then it is necessary to write constants in quotes in the body "" - test19
    • @SOFL: Well, this should be a property, not a local variable. And what does “body” mean in your case? - VladD