I’m trying to check with a converter if a Image Source exists in local storage. If not go with the external url.
<Image Source="{Binding Image, Converter={StaticResource ImageCacheConverter}}"/>
This is my converter so far:
public object Convert(object value, Type targetType, object parameter, string language)
{
return IfFileExist((string)value, "localimage.png");
}
public async Task<string> IfFileExist(string value, string filename)
{
var folder = ApplicationData.Current.LocalFolder;
var getFilesAsync = await folder.GetFilesAsync(CommonFileQuery.OrderByName);
var file = getFilesAsync.FirstOrDefault(x => x.Name == filename);
if (file != null)
{
return "ms-appdata:///local/" + filename;
}
return (string)value;
}
The major problem I’m facing is having async inside an IValueConverter. But i need the return o the IfFileExist to change the image source.
Thanks in Advance.
I think you want don’t want your
IfFileExistmethod to run asychronously. But that’s what is happening because of the usage ofawait.Try changing it to this:
Instead of using
awaitwe are accessing theResultproperty of the task that is returned byGetFilesAsync, blocking our method until the task finished.Your original code is quasi-equivalent to the following: