我有大量的圖片需要加載到我的wpf應用程序中。我用BackgroundWorker嘗試了它,但它不能在顯示圖像的位置創建togglebutton。在wpf中加載很多圖片
有沒有更好的方法來加載大量的圖像?它們需要可選,因爲用戶可以選擇圖像。
這裏有一點到目前爲止我的代碼:
<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;
}
[與WPF線程加載圖像]的可能重複(http://stackoverflow.com/questions/1738978/loading-image-in-thread-with-wpf) –
很難說沒有看過任何的代碼。 – Clemens
@Clemens增加了一些代碼 – Calypoter