2016-05-11 7 views
2

私はImageCellのリストをバインドするためにListViewでデータバインディングを使用しています。イメージは、アプリケーションデータとしてデバイスにローカルに保存されたファイルです。Xamarin.FormsローカルファイルへのImageCellバインド

Windowsでは、ファイルへの絶対パスまたは相対パスを使用できません。ファイル:// URIに変換する必要があります。残念ながら、Androidでは、file:// URIは機能せず、パスである必要があります。

現在、ターゲットプラットフォームに応じてビューモデルで異なる値を使用して問題を回避しています。これよりもよりよい解決策はあります:

if (Device.OS == TargetPlatform.Windows) { 
    result.uri = new Uri(uri).AbsoluteUri; 
} 

XAML:

<ListView.ItemTemplate> 
    <DataTemplate> 
    <ImageCell ImageSource="{Binding Uri}" 
       Text="{Binding Name}"> 
    </ImageCell> 
    </DataTemplate> 
</ListView.ItemTemplate> 

Uriのタイプがあり、文字列、私が代わりにUriImageSourceを使用する必要がありますか?

答えて

1

コンバータと依存関係サービスを作成して解決しました。

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> 

コンバータ

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; 
    } 
+0

うわー、これは本当に複雑です。プラットフォームがWindowsであるかどうかに応じて、ビューモデルのfile:// URIに変換するほうが簡単でしょうか?すなわち、https://github.com/Azure-Samples/app-service-mobile-dotnet-todo-list-files/blob/master/src/client/MobileAppsFilesSample/ViewModels/TodoItemImageViewModel.cs#L31。 –

+0

Windowsのような単純な解決策が見つからないので、上記の解決策で解決しました。簡単な方法を見つけたら、投稿してください。 – user3509981

+0

私の現在のソリューションで私の質問を更新しました。ちょうど2行のコードです。 –

関連する問題