2017-03-02 66 views
1

我想在listview中添加我的項目。這是我的課程;如何在wpf應用程序的listview中添加項目?

FindFace.Show.Response response = await _api.Show_Face(lb_GalleryList.SelectedItem.ToString());   
    if (response.results.Count != 0) 
    { 
     List<FaceImages> faceImages = new List<FaceImages>(); 
     for (int i = 0; i < response.results.Count; i++) 
     { 
     faceImages.Add(new FaceImages() { Face_id = response.results[i].person_id.ToString(), Face_thumbnail = LoadImage(response.results[i].thumbnail) }); 
     } 
     lv_Photos.ItemsSource = faceImages;      
    } 

在faceImages中,這是它的樣子; enter image description here

而且這裏是我的xaml文件的樣子;

<ListView x:Name="lv_Photos" HorizontalAlignment="Stretch" VerticalAlignment="Top"> 
       <ItemsControl.ItemsPanel> 
        <ItemsPanelTemplate> 
         <UniformGrid Columns="5" HorizontalAlignment="Stretch" /> 
        </ItemsPanelTemplate> 
       </ItemsControl.ItemsPanel> 
       <DataTemplate> 
        <StackPanel Orientation="Vertical" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"> 
         <Image Source="{Binding Face_thumbnail}" HorizontalAlignment="Stretch" VerticalAlignment="Top" Stretch="UniformToFill" /> 
         <TextBlock Text="{Binding Face_id}" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" /> 
        </StackPanel> 
       </DataTemplate> 
      </ListView> 

但是,當我試圖把faceImages放在ItemsSource這裏;

lv_Photos.ItemsSource = faceImages; 

應用程序使

An exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll but was not handled in user code 

Additional information: Items collection must be empty before using ItemsSource. 

我不明白我怎麼能傳遞faceImages類我的列表視圖元素。

+0

你必須ListView.Items東西(所以例如,你手動添加一些項目在XAML ListView控件或以某種方式加入代碼之前的東西項目集合),所以你不能使用的ItemsSource,因爲Items和ItemsSource是互斥的。 – Evk

+0

@Evk我想爲這種情況找到一些解決方案,如有必要,我可以重寫所有內容。 – goGud

+0

也應該使用ObservableCollection而不是列表作爲itemSource或綁定不會更新 – MikeT

回答

2

您不小心將DataTemplate作爲子項添加到ListView本身中。這就是爲什麼Items收集不是空的,ItemsSource不能使用,因爲它們是互斥的。相反,使用ListView.ItemTemplate

<ListView x:Name="lv_Photos" 
      HorizontalAlignment="Stretch" 
      VerticalAlignment="Top"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <UniformGrid Columns="5" 
         HorizontalAlignment="Stretch" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Vertical" 
         VerticalAlignment="Stretch" 
         HorizontalAlignment="Stretch"> 
       <Image Source="{Binding Face_thumbnail}" 
         HorizontalAlignment="Stretch" 
         VerticalAlignment="Top" 
         Stretch="UniformToFill" /> 
       <TextBlock Text="{Binding Face_id}" 
          HorizontalAlignment="Stretch" 
          VerticalAlignment="Bottom" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 
+0

你真棒..我不知道我是如何錯過它的。謝謝.. – goGud

+0

@Evk抱歉,在錯誤的地方發表評論 – MikeT

相關問題