我正在尝试构建xamarin图像上传应用程序。在上传到服务器之前,我想显示本地图像,之后,我想显示来自服务器url的图像。如果我使用Image source,它在本地和服务器上都工作得很好。但是出现了服务器镜像缓存问题。
<Image Grid.Row="0"
Source="{Binding Url}"
Aspect="AspectFill"
HeightRequest="60"
BackgroundColor="black"
WidthRequest="60"/>因此,为了禁用缓存,我使用了UriImageSource,它在服务器url上工作,但它不显示本地图像。
<Image Grid.Row="0"
Aspect="AspectFill"
HeightRequest="60"
BackgroundColor="black"
WidthRequest="60">
<Image.Source>
<UriImageSource Uri="{Binding Url}"
CachingEnabled="False"/>
<!--FileImageSource File="{Binding Url}"/-->
</Image.Source>
</Image>是否可以在此图像中同时使用文件和uri图像源?谢谢你的帮助。
发布于 2021-03-07 14:36:19
选项1:-使用绑定Url
创建转换器(ImageConverter)。下面的ImageConverter有用于测试的虚拟代码。它使用静态字段(请不要使用静态字段)。您可以绑定Url属性,根据Url可以确定图像源是远程url还是本地图像。并返回UriImageSource或直接字符串(本地镜像)。在ViewModel中,Uri属性的初始值将是本地映像,一旦接收到远程映像,就会将Uri设置为远程映像,并引发属性更改事件。
//ImageConverter.cs
public class ImageConverter : IValueConverter
{
public static int count = 1;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
count++;
var imageUri = System.Convert.ToString(value);
if (imageUri.Contains("http") && (count % 2 == 0))
{
UriImageSource uriImageSource = new UriImageSource();
uriImageSource.Uri = new Uri(imageUri);
uriImageSource.CachingEnabled = false;
return uriImageSource;
}
else
{
return imageUri;//Local image
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
//Xaml header
xmlns:local="clr-namespace:Monkeys.Converter"
<ContentPage.Resources>
<ResourceDictionary>
<local:ImageConverter x:Key="imgConv" />
</ResourceDictionary>
</ContentPage.Resources>
//Xaml content
<Image Grid.Row="0"
Source="{Binding Url, Converter={StaticResource imgConv}}"
Aspect="AspectFill" HeightRequest="60"
BackgroundColor="black" WidthRequest="60"
HorizontalOptions="CenterAndExpand">
</Image>选项2:-使用ConverterParameter
根据我的调查,xamarin.forms不支持ConverterParameter绑定。所以,这里有一个work around。在您的模型/视图模型IsRemoteUri中创建一个新的bool属性。一旦获取远程映像,初始IsRemoteUri将为false,然后将IsRemoteUri更改为true。将IsRemoteUri绑定到ConverterParameter。
和转换器将如下代码。
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var imageUri = System.Convert.ToString(value);
var isRemoteUri = (bool)parameter;
if (isRemoteUri)
{
var uriImageSource = new UriImageSource();
uriImageSource.Uri = new Uri(imageUri);
uriImageSource.CachingEnabled = false;
return uriImageSource;
}
else
{
return imageUri;//Local image
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}我已经使用这个code进行了测试
https://stackoverflow.com/questions/66494364
复制相似问题