2012-05-23 28 views
2

在大多數教程中,我已經看到了作者使用和可觀察集合的Windows Phone 7 Silverlight應用程序中的數據綁定。由於我的數據在我綁定後不會改變,這是完全必要的嗎?爲什麼我不能使用列表?綁定必須是可觀察的集合,爲什麼這不起作用?

每種方法的優點和缺點是什麼? :)

此外,爲什麼下面的代碼不起作用?它看起來應該給我。

C#貢獻者類

public class Contributor 
    { 
      public string Name; 
      public string RSSUrl; 

      public Contributor(string name, string rssURL) 
      { 
        Name = name; 
        RSSUrl = rssURL; 
      } 
    } 

C#項目綁定

  List<Contributor> people = new List<Contributor> { new Contributor("Danny", "www.dannybrown.com") }; 
     contributorsListBox.ItemsSource = people; 

XAML

<!--Panorama item two--> 
     <!--Use 'Orientation="Horizontal"' to enable a panel that lays out horizontally--> 
     <controls:PanoramaItem Header="contributors"> 
      <!--Double line list with image placeholder and text wrapping--> 
      <ListBox x:Name="contributorsListBox" Margin="0,0,-12,0" ItemsSource="{Binding}"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal" Margin="0,0,0,17"> 
          <!--Replace rectangle with image--> 
          <Rectangle Height="100" Width="100" Fill="#FFE5001b" Margin="12,0,9,0"/> 
          <StackPanel Width="311"> 
           <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" /> 
           <TextBlock Text="{Binding RSSUrl}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/> 
          </StackPanel> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 
     </controls:PanoramaItem> 

正如你所看到的,每個項目都有一個與之關聯的紅色矩形。我確信綁定是有用的,因爲每當我更改列表中的貢獻者數量時,就會出現正確數量的紅色矩形。

任何人有任何想法?

謝謝, 丹尼。

回答

3

您的貢獻者類需要具有屬性,而不僅僅是公共字段。

public class Contributor 
{ 
     public string Name { get; set; } 
     public string RSSUrl { get; set; } 

     public Contributor(string name, string rssURL) 
     { 
       Name = name; 
       RSSUrl = rssURL; 
     } 
} 

編輯:至於你的問題,ObservableCollections只需要在您的數據會改變(即您要添加或刪除的記錄)。您確實可以綁定到列表或IEnumerables。

+0

這是一個簡單的修復。令人驚訝的是,我經常看不到眼前有什麼。謝謝 :) – DanTonyBrown