Silverlight Windows Phone Databinding -- noob question

Nat*_*ate 1 .net data-binding silverlight wpf windows-phone-7

I have a basic Windows Phone List application, with code like this in the MainViewModel class

// CODE THAT WORKS --

Items.Clear();

foreach (var itm in e.Result)
    Items.Add(itm);

Count = Items.Count;

// CODE THAT DOES NOT WORK -- I'm trying to understand WHY

Items = e.Result;
Run Code Online (Sandbox Code Playgroud)

The databinding Xaml looks like this:

<DataTemplate>
    <StackPanel x:Name="DataTemplateStackPanel" Orientation="Horizontal">
        <Image x:Name="ItemImage" Source="/AppName;component/Images/ArrowImg.png" Height="43" Width="43" VerticalAlignment="Top" Margin="10,0,20,0"/>
        <StackPanel>
            <TextBlock x:Name="ItemText" Text="Event Name" Margin="-2,-13,0,0" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
            <TextBlock x:Name="DetailsText" Text="{Binding Path=Description}" Margin="0,-6,0,3" Style="{StaticResource PhoneTextSubtleStyle}"/>
        </StackPanel>
    </StackPanel>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

I think I have a misunderstanding of how ObservableCollection and INotifyPropertyChanged work, because I'm thinking that this code should work. Databinding to NonCollection items is working as I'd expect with my INotifyPropertyChanged implementation.

Ane*_*ero 5

虽然你没有为Items属性包含代码片段,但我猜想问题是你在修改属性的值时没有触发PropertyChanged事件(也就是说,更改对另一个对象的引用).如果要保留不起作用的代码,则应实现Items属性,如下所示:

private IEnumerable<Item> items;

public IEnumerable<Item> Items
  {
      get { return this.items; }
      set
      {
          this.items = value;
          // Call OnPropertyChanged whenever the property is updated
          OnPropertyChanged("Items");
      }
  }

  protected void OnPropertyChanged(string name)
  {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
          handler(this, new PropertyChangedEventArgs(name));
      }
  }
Run Code Online (Sandbox Code Playgroud)

使用此实现,您不需要Items集合是ObservableCollection,但每次您想要修改它(添加或删除项目)时,您应该完全替换它.

当然,您可以将类型保留为ObservableCollection而不是IEnumerable,但要考虑此类集合相对于List或Array等其他类型的开销.