Reputation: 2790
I'm trying to bind in a Listview to a ObservableCollection. I get the following error.
Debugger Message:
Error: Converter failed to convert value of type 'System.Collections.ObjectModel.ObservableCollection`1' to type 'ImageSource'; BindingExpression: Path='PictureSource' DataItem='MeetFriends.MainViewModel.View'; target element is 'Windows.UI.Xaml.Controls.Image' (Name='null'); target property is 'Source' (type 'ImageSource').
My ListView:
<ListView ItemsSource="{Binding}" DataContext="{Binding FriendsData, Source={StaticResource view}}" Margin="0,0,2,0" x:Name="ListUI" Loaded="ListUI_Loaded" Background="WhiteSmoke"
ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollMode="Enabled" >
<ListView.Header>
<Grid Margin="14,0,0,14" >
<TextBlock Foreground="Black" TextWrapping="WrapWholeWords">People you are friends with and using MeetFriends:</TextBlock>
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Margin="0,14,0,0" >
<StackPanel Orientation="Horizontal" >
<TextBlock Text="{Binding name}" Margin="0,0,14,0" FontSize="{Binding Fontsize, Source={StaticResource view}}" FontFamily="Segoe UI Black"></TextBlock>
<Image Source="{Binding PictureSource, Source={StaticResource view}}" Height="100" Width="100">
</Image>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And the Binding is to:
public ObservableCollection<ImageSource> PictureSource
{
get { return _pictureSource; }
set { _pictureSource = value; OnPropertyChanged("_pictureSource"); }
}
Adding Values is looking like this in the code:
foreach(object x in f.data) {
view.FriendsData.Add(f.data[i]);
view.PictureSource.Add(new BitmapImage() { UriSource = new Uri("https://graph.facebook.com/v2.5/" + view.FriendsData[i].id.ToString() + "/picture?redirect=true") });
Debug.WriteLine("A new object has been added to friendsdata and picturesource ["+i+"]");
i++;
}
Upvotes: 0
Views: 4610
Reputation: 1491
Error is pretty self explanatory, you should bind your image to a field of data context of the current item, which is item of FriendsData collection.
You may bind your image directly to id and use a converter, that will convert that string to an ImageSource:
<Image Source="{Binding id, Converter={StaticResource idToImageConverter}}" Height="100" Width="100" />
Converter:
public class IdToImageConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return new BitmapImage() { UriSource = new Uri("https://graph.facebook.com/v2.5/" + value.ToString() + "/picture?redirect=true") }
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
More information on value converters
Upvotes: 1