Hi,
i try to bind a Base64 (ImageResourceStream) to an image in XAML but end up everytime in an unhandled exception.
This is my code:
ViewModel:
private ObservableCollection<WebImageSource> _imageSources; public ObservableCollection<WebImageSource> ImageSources { get { return _imageSources; } set { if (_imageSources != value) { _imageSources = value; OnPropertyChanged(nameof(ImageSources)); } } } public GalleryViewModel() { Title = "Galery"; _testService = new TestService(); ImageSources = new ObservableCollection<WebImageSource>(); this.OnOpenView += async (o, e) => { ImageSources = new ObservableCollection<WebImageSource>((await _testService.Get())); }; }
WebImageSource
just contains a property named Base64
and some meta data.
This is my View:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyApp.Views.GalleryPage" xmlns:c="clr-namespace:MyApp.Converters" Title="{Binding Title}" > <ContentPage.Resources> <ResourceDictionary> <c:Base64ImageSourceConverter x:Key="ImageConverter" /> </ResourceDictionary> </ContentPage.Resources> <StackLayout> <ListView ItemsSource="{Binding ImageSources}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Image Source="{Binding Base64, Converter={StaticResource ImageConverter}}}" Grid.Row="0" Grid.RowSpan="3" Grid.Column="0" HorizontalOptions="Center" HeightRequest="50" VerticalOptions="Center"> </Image> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout> </ContentPage>
At least the converter:
public class Base64ImageSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var base64 = (string)value; if (base64 == null) return null; return ImageSource.FromStream(() => { return new MemoryStream(System.Convert.FromBase64String(base64)); }); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } }
The converter is entered without problems and returns an ImageSource.
Seems that the exception is thrown on binding the new ObservableCollection to my view...
What i am doing wrong here? Can somebody help, please?
Answers
@senz.7857
What is the exception and stack trace that you are getting?
Issue is {Binding Base64, Converter={StaticResource ImageConverter}}}, one too many }