I am trying to load in (asynchronously) a picture from a directory which shall be displayed when loaded.
In my XAML-Code I bound some List to the data template:
<ScrollViewer Grid.Row="2">
<ItemsControl x:Name="display">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Source ,IsAsync=True}" Width="100" Height="100" Margin="5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
Together with a class created:
public class ImageViewModel
{
public ImageViewModel(string path)
{
Path = path;
}
public string Path { get; }
private BitmapImage image;
public BitmapImage Source
{
get
{
if (image == null)
{
image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.DecodePixelWidth = 500;
image.UriSource = new Uri(Path);
image.EndInit();
image.Freeze();
}
return Source;
}
}
}
with the rest of code:
ObservableCollection<ImageViewModel> images { get; } = new ObservableCollection<ImageViewModel>();
string workingDir = "some_path";
List<string> files = new List<string>();
public MainWindow()
{
InitializeComponent();
display.ItemsSource = images;
DataContext = this;
}
private void On_Loaded(object sender, RoutedEventArgs e)
{
files = DirSearch(workingDir); //returns List of strings with paths
foreach (string file in files)
{
images.Add(new ImageViewModel(file));
}
}
So, the code executes and does something, but does not display any images: