I have a huge amount of pictures that need to be loaded in my wpf app. I tried it with a BackgroundWorker but it cannot create the togglebutton where the image is show on.
Is there a better way to load a huge amount of images? They need to be selectable because the user can choose an image.
Here's a bit of my code so far:
<WrapPanel Name="mFolderImages">
<ToggleButton Width="150" Margin="5" Style="{StaticResource ImageList}">
<ToggleButton.Content>
<Image Source="/Managment;component/images/example.png" />
</ToggleButton.Content>
</ToggleButton>
</WrapPanel>
private void GetFolderImagesThreadFinished(object sender, RunWorkerCompletedEventArgs e) {
if (e.Result != null && e.Result is List<BitmapImage>) {
List<BitmapImage> images = (List<BitmapImage>)e.Result;
foreach (var image in images) {
Image img = new Image();
img.Source = image;
img.Margin = new Thickness(5);
ToggleButton btn = new ToggleButton();
btn.Content = img;
btn.Width = 150;
btn.Margin = new Thickness(5);
btn.IsEnabled = true;
btn.Click += ChangeSelectedImage;
btn.Style = this.FindResource("ImageList") as Style;
mFolderImages.Children.Add(btn);
}
}
mProgress.Visibility = Visibility.Collapsed;
mFolderImages.IsEnabled = true;
}
private void GetFolderImagesThread(object sender, DoWorkEventArgs e) {
string imagePath = Config.GetValue("ImagePath");
if (!Directory.Exists(imagePath)) return;
string[] files = Directory.GetFiles(imagePath);
int progress = 0;
List<BitmapImage> images = new List<BitmapImage>();
foreach(var file in files) {
if (file.EndsWith(".jpg") || file.EndsWith(".png")) {
try {
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(file, UriKind.Absolute);
bmp.EndInit();
bmp.Freeze();
images.Add(bmp);
} catch (Exception ex) {
Console.Write(ex.Message);
}
}
++progress;
mThread.ReportProgress((int)((progress / (float)files.Length) * 100));
}
e.Result = images;
}