[英]How to release Image from Image Source in WPF
正在加載如下圖像
XAML
<Image Stretch="None" Grid.Row="16" Height="70" HorizontalAlignment="Left" Name="imgThumbnail" VerticalAlignment="Top" Width="70" Grid.RowSpan="3" Margin="133,1,0,0" Grid.Column="2" Grid.ColumnSpan="2" />
代碼背后
if (Path.GetFileNameWithoutExtension(filePath).ToLower().Contains(slugName.ToLower() + "_70x70"))
{
imgThumbnail.BeginInit();
imgThumbnail.Stretch = Stretch.UniformToFill;
imgThumbnail.Source = new BitmapImage(new Uri(filePath));
imgThumbnail.EndInit();
count = count + 1;
}
上面的代碼可以正常工作,現在,我的縮略圖旁邊有一個刪除按鈕,如果調用的刪除按鈕我想從源位置刪除所有圖像。
這是刪除圖像文件的代碼
internal int Remove(string slugName, DirectoryInfo outputFolder)
{
Helper.MetadataView.imgThumbnail.Source = null;
foreach (string filePath_ToBeDeleted in filePathList_ToBeDeleted)
{
if (File.Exists(filePath_ToBeDeleted))
{
Helper.MetadataView.imgThumbnail.IsEnabled = false;
File.Delete(filePath_ToBeDeleted);
count += 1;
}
}
return count;
}
return 0; // slugName == null
}
我試圖將源設置為null並刪除,但是它引發如下異常
該進程無法訪問文件'\\ serv1 \\ Dev \\ Images \\ 730_Test4_0406_70x70.jpg',因為該文件正在被另一個進程使用。
不知道如何處理,請有人指導我。
如果要刪除或移動Image
不應在應用程序中直接使用該Image
。
imgThumbnail.Source = new BitmapImage(new Uri(filePath));
相反,請執行以下操作:
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filePath);
image.EndInit();
imgThumbnail.Source = image;
欲了解更多,請閱讀此
為了獲得良好的代碼重用,可以使用綁定轉換器:
namespace Controls
{
[ValueConversion(typeof(String), typeof(ImageSource))]
public class StringToImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is string valueString))
{
return null;
}
try
{
ImageSource image = BitmapFrame.Create(new Uri(valueString), BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.OnLoad);
return image;
}
catch { return null; }
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
還有一個用於綁定的字符串,例如
public string MyImageString { get; set; } = @"C:\test.jpg"
在UI中,使用了轉換器,在我的例子中,使用的是名為“ Controls”的庫
<Window x:Class="MainFrame"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:Controls;assembly=Controls">
<Window.Resources>
<controls:StringToImageSourceConverter x:Key="StringToImageSourceConverter" />
</Window.Resources>
<Grid>
<Image Source="{Binding MyImageString, Converter={StaticResource StringToImageSourceConverter}}" />
</Grid>
</Window>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.