2013-02-18 74 views
0

我想爲Windows Phone 7製作我自己的媒體播放器,對於第一步,我想在我的媒體庫中顯示所有歌曲的列表以選擇它們。 我的理解ListBox中,我只是說出像我的類的屬性,這將是「歌」 texblocks將歌曲列表添加到列表框

<ListBox FontSize="30" Name="songListGUI" Height="330" Margin="0,120,0,0"> 
    <Button Width="430" Height="60" BorderThickness="0" Margin="0" > 
      <Button.Content> 
       <StackPanel Orientation="Horizontal" Width="420" Height="auto"> 
       <TextBlock Name="Name" Text="{Binding Name}" FontSize="22"></TextBlock> 
       <TextBlock Text=" - " FontSize="22"></TextBlock> 
       <TextBlock Name="Artist" Text="{Binding Artist}" FontSize="22"></TextBlock> 
       </StackPanel> 
      </Button.Content> 
     </Button> 
    </ListBox> 

,現在我想,我應該處理我的歌曲列表的GUI和我嘗試這樣做,有:

songListGUI.ItemsSource = songs; 

但後來我得到一個「InvalidOperationException異常」 - 物品收集必須在使用ItemsSource前空。 我發現了這樣的幾個問題,並且他們都創建了一個新類,以顯示此內容。但我想堅持歌班,因爲它很方便:/ 你知道我在這裏做錯了嗎?

編輯: 我剛找到解決方案。不知道爲什麼,但.xaml中的這一變化使我達到:):

<ListBox FontSize="30" Name="songListGUI" Height="330" Margin="0,120,0,0"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Button Width="430" Height="60" BorderThickness="0" Margin="0" > 
       <Button.Content> 
         <StackPanel Orientation="Horizontal" Width="420" Height="auto"> 
          <TextBlock Name="Name" Text="{Binding Name}" FontSize="22"></TextBlock> 
          <TextBlock Text=" - " FontSize="22"></TextBlock> 
          <TextBlock Name="Artist" Text="{Binding Artist}" FontSize="22"></TextBlock> 
         </StackPanel> 
        </Button.Content> 
      </Button> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

任何人都可以向我解釋這個嗎?

回答

2

ListBox是ItemsControl。 ItemsControl的內容映射到Items屬性。所以這樣做:

<ListBox> 
    <SomeContent/> 
</ListBox> 

你正在設置Items屬性爲<SomeContent/>。由於您不被允許設置Items屬性和ItemsSource屬性,因此會發生異常。

當你這樣做:

<ListBox> 
    <ListBox.ItemTemplate>...</ListBox.ItemTemplate> 
</ListBox> 

你沒有設置你設置列表框的屬性,所以沒有衝突的內容。