2016-03-06 80 views
0

我想在Listview中綁定到ObservableCollection。我收到以下錯誤。Mvvm xaml綁定轉換器無法轉換值錯誤

調試消息:

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').

我的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> 

並且綁定是:

public ObservableCollection<ImageSource> PictureSource 
    { 
     get { return _pictureSource; } 
     set { _pictureSource = value; OnPropertyChanged("_pictureSource"); } 
    } 

添加值正在尋找這樣的代碼:

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

回答

0

錯誤是非常明顯的,您應該將圖像綁定到當前項目的數據上下文的字段,這是項目的FriendsData集合。

可以將您的圖像直接綁定到ID和使用轉換器,將這個字符串轉換爲ImageSource的:

<Image Source="{Binding id, Converter={StaticResource idToImageConverter}}" Height="100" Width="100" /> 

轉換器:

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

+0

@AntonDynlov你是對的,爲什麼我沒有看到IValueConverter很容易:/ –

+0

沒關係,它發生了:) –