ListBox加载大量图片时,如果采用同步方法,页面出来速度太慢,最好办法就是采用异步加载了,直接上代码,如下:
前台页面完整代码:
<Window x:Class="异步加载图片.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Loaded="Window_Loaded" WindowState="Maximized" Background="#FF199864">
<Window.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Padding" Value="3,3,3,3"/>
</Style>
</Window.Resources>
<Grid>
<ListBox x:Name="list" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Disabled"
ScrollViewer.PanningRatio="2.0" ScrollViewer.CanContentScroll="False">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center" VirtualizingStackPanel.IsVirtualizing="True"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.Background>
<SolidColorBrush />
</ListBox.Background>
</ListBox>
</Grid>
</Window>
后台代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory+"Photo"))
{
string file1 = file;//必须有,不妨试试不加这段代码,看看效果就明白了
Dispatcher.BeginInvoke((Action)(() =>
{
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(file1,UriKind.RelativeOrAbsolute);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
double ww = bitmap.PixelWidth;
double hh = bitmap.PixelHeight;
Image image = new Image();
image.Source = bitmap;
image.Height = 200;
image.Width = 200 * (ww / hh);
this.list.Items.Add(image);
}));
}
}
}
这样的方法页面出来速度是快了,但图片加载速度还是慢,原本预想结果是图片是一张一张加在进来的,却图片是全部一下加载到界面上,所以速度显得有点慢。解决办法
采用 Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => {.......}