实现 INotifyPropertyChanged 有什么用?

What is the use of implementing the INotifyPropertyChanged?

实现 INotifyPropertyChanged 有什么用,如果没有它,下面的代码也能正常工作?

<DataGrid ItemsSource="{Binding Items}" 
          AutoGenerateColumns="False">
    <DataGrid.Columns>

        <DataGridTextColumn Header="Name" 
                            Binding="{Binding Name}"/>

        <DataGridComboBoxColumn Header="Color" 
                                SelectedItemBinding="{Binding Color}">
            <DataGridComboBoxColumn.ElementStyle>
                <Style TargetType="ComboBox">
                    <Setter Property="ItemsSource" Value="{Binding Colors}"/>
                </Style>
            </DataGridComboBoxColumn.ElementStyle>
            <DataGridComboBoxColumn.EditingElementStyle>
                <Style TargetType="ComboBox">
                    <Setter Property="ItemsSource" Value="{Binding Colors}"/>
                </Style>
            </DataGridComboBoxColumn.EditingElementStyle>
        </DataGridComboBoxColumn>
    </DataGrid.Columns>
</DataGrid>

<Button Content="Change Colors" Click="Change"/>

   public class Data
   {
      private ObservableCollection<Item> _items;
      public ObservableCollection<Item> Items
      {
         get { return _items; }

      }

      public Data()
      {
         _items = new ObservableCollection<Item>();
         _items.Add(new Item() { Name = "A" });
         _items.Add(new Item() { Name = "B" });
      }

      public void Change()
      {
         _items[0].Colors.RemoveAt(1);
      }
   }

   public class Item
   {
      public string Name { get; set; }
      public string Color { get; set; }


      private IList<string> _colors;
      public IList<string> Colors
      {
         get { return _colors; }
      }


      public Item()
      {
         _colors = new List<string> { "Green", "Blue" };
         Color = _colors[0];
      }
   }

ObservableCollection<T> 实现了 INotifyCollectionChangedINotifyPropertyChanged 接口,所以如果您只是想在运行时从源集合中添加和删除项目,则不需要您实现 INotifyPropertyChanged 接口。

如果您希望能够例如更新 NameColor [=36=,则必须在您的自定义 Item class 中实施它] 虽然是动态的。

如果您将 ItemName 属性 设置为新值,除非 Item class 实现 INotifyPropertyChanged 接口并在名称 属性 的 setter 中引发 PropertyChanged 事件。

What if I want to have a custom functionality when the collection changes! For example throw a message! Should I use List instead of ObservableCollection and throw that message in the property's `´set´?

您可以处理 ObservableCollection<T>CollectionChanged 事件。