Silverlight的Windows Phone的数据绑定 - noob问题

问题描述:

我有一个基本的Windows Phone应用程序列表,用code这样的MainViewModel类

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;

数据绑定的XAML看起来是这样的:

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>

我想我的ObservableCollection和INotifyPropertyChanged的是如何工作的误解,因为我认为这code应该工作。数据绑定到NonCollection项目正在按我期待着与我的INotifyPropertyChanged的实施。

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.

你们虽然没有包括在code段为项目属性,我猜想,问题是,你是不是发射PropertyChanged事件时,修改所述属性的值(即,改变参考至另一对象)。 如果你想保持code不工作,你应该实现这样的项目属性:

Though you haven't included the code snippet for the Items property, I would guess that the problem is that you are not firing the PropertyChanged event when modifying the value of the property (that is, changing the reference to another object). If you want to keep the code that doesn't work, you should implement the Items property like this:

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));
      }
  }

通过这个实现,你不需要Items集合是一个ObservableCollection,但每次你想修改(添加或删除项目),你应该完全取代它。

With this implementation, you wouldn't need the Items collection to be an ObservableCollection, but each time you would want to modify it (adding or removing items), you should replace it entirely.

当然,你可以保持类型的ObservableCollection,而不是IEnumerable的,但考虑到开销,这种集合有超过其他类似的列表或数组。

Of course you could keep the type as ObservableCollection instead of IEnumerable but take into account the overhead that this kind of collection has over others like List or Array.