2012-05-23 24 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