Xamarin.forms Forms ImageCell绑定到本地文件
我在ListView中使用数据绑定来绑定ImageCells列表。图像是作为应用程序数据本地存储在设备上的文件 在Windows上,使用文件的绝对或相对路径不起作用,我必须将其转换为file://URI。不幸的是,在Android上,//URI文件不起作用,它需要一个路径 我目前正在解决这个问题,根据目标平台的不同,在视图模型中使用不同的值。有没有比这更好的解决方案:Xamarin.forms Forms ImageCell绑定到本地文件,xamarin.forms,Xamarin.forms,我在ListView中使用数据绑定来绑定ImageCells列表。图像是作为应用程序数据本地存储在设备上的文件 在Windows上,使用文件的绝对或相对路径不起作用,我必须将其转换为file://URI。不幸的是,在Android上,//URI文件不起作用,它需要一个路径 我目前正在解决这个问题,根据目标平台的不同,在视图模型中使用不同的值。有没有比这更好的解决方案: if (Device.OS == TargetPlatform.Windows) { result.uri = new
if (Device.OS == TargetPlatform.Windows) {
result.uri = new Uri(uri).AbsoluteUri;
}
Xaml:
Uri
的类型是string,我需要使用UriImageSource
吗?我通过创建转换器和依赖项服务解决了这个问题
Xaml
<ContentPage.Content>
<StackLayout VerticalOptions="FillAndExpand" Padding="5,20,5,0" >
<ListView x:Name="list" ItemsSource="{Binding MyList}">
<ListView.ItemTemplate>
<DataTemplate>
<ImageCell Text="{Binding Name}" ImageSource="{Binding ImagePath, Converter={StaticResource AndroidImageInvert}}">
</ImageCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
哇,这真的很复杂。根据平台是否为Windows,在视图模型中转换为文件://URI不是更容易吗?也就是说,我找不到像Windows这样简单的解决方案,所以用上面的解决方案解决了。如果你遇到了更简单的方法,请发布它。我用我当前的解决方案更新了我的问题,它只是两行代码。
<ContentPage.Content>
<StackLayout VerticalOptions="FillAndExpand" Padding="5,20,5,0" >
<ListView x:Name="list" ItemsSource="{Binding MyList}">
<ListView.ItemTemplate>
<DataTemplate>
<ImageCell Text="{Binding Name}" ImageSource="{Binding ImagePath, Converter={StaticResource AndroidImageInvert}}">
</ImageCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
public class ByteImageConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
string fileName = value as string;
return ImageSource.FromStream(() => new MemoryStream(DependencyService.Get<IWRDependencyService>().GetImageBytes(fileName)));
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public byte[] GetImageBytes(string fileName)
{
fileName = fileName.Replace(".jpg", "").Replace(".png", "");
var resId = Forms.Context.Resources.GetIdentifier(
fileName.ToLower(), "drawable", Forms.Context.PackageName);
var icon = BitmapFactory.DecodeResource(Forms.Context.Resources, resId);
var ms = new MemoryStream();
icon.Compress(Bitmap.CompressFormat.Png, 0, ms);
byte[] bitmapData = ms.ToArray();
return bitmapData;
}