wpf imagesource=null 同时清空内存
确保imagesource只有image控件引用的情况下,这么赋值:
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(list[current], UriKind.RelativeOrAbsolute);
image.EndInit();
Image imageControl = new Image();
imageControl.Source = image;
测试代码:
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
List
public MainWindow()
{
InitializeComponent();
string dir = @"C:\Users\Sam\Pictures\大图";
for (int i = 0; i < 6; i++)
{
list.Add($"{dir}{i}.png");
}
}
int current = 0;
int max = 5;
//HttpClient httpClient = new HttpClient();
private /*async*/ void Button_Click(object sender, RoutedEventArgs e)
{
//不清空图片控件,清除每个图片控件的source
foreach (var item in container.Children)
{
if (item is Image)
{
Image img = (Image)item;
img.Source = null;
}
}
////清空图片控件--ok,可以清空内存
//var listx = new List<Image>();
//for (int i = 0; i < container.Children.Count; i++)
//{
// if (container.Children[i] is Image)
// {
// Image img = (Image)container.Children[i];
// listx.Add(img);
// }
//}
//foreach (var item in listx)
//{
// container.Children.Remove(item);
//}
GC.Collect();
//Image image = new Image();
//image.Source = new BitmapImage(new Uri(list[current], UriKind.RelativeOrAbsolute));
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(list[current], UriKind.RelativeOrAbsolute);
image.EndInit();
Image imageControl = new Image();
imageControl.Source = image;
container.Children.Add(imageControl);
current++;
if (current > max)
{
current = 0;
}
}
}