【问题标题】:What is the use of implementing the INotifyPropertyChanged?实现 INotifyPropertyChanged 有什么用?
【发布时间】:2017-02-03 11:11:46
【问题描述】:

如果没有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 已经实现了 INotifyPropertyChanged,所以当它的数据发生变化时它可以开箱即用。
  • 现在尝试在加载后更改您的数据,并查看 UI 是否显示更改
  • ObservableCollection 实现 INotifyPropertyChanged MSDN
  • 正如@Equalsk 和 Kilazur 已经说过的,ObservableCollection 实现了开箱即用的 InotifyPropertyChanged
  • 你可以处理 ObservableCollection 的 CollectionChanged 事件。我将此添加到我的答案中。

标签: c# wpf mvvm inotifypropertychanged


【解决方案1】:

ObservableCollection&lt;T&gt; 实现了INotifyCollectionChangedINotifyPropertyChanged 接口,因此如果您只想在运行时从源集合中添加和删除项目,则无需实现INotifyPropertyChanged 接口。

如果您希望能够动态更新 NameColor 属性,则必须在自定义 Item 类中实现它。

如果您将ItemName 属性设置为新值,除非Item 类实现INotifyPropertyChanged 接口并在Name 属性的设置器。

如果我想在集合更改时拥有自定义功能怎么办!例如抛出一条消息!我应该使用 List 而不是 ObservableCollection 并将该消息扔到属性的“set”中吗?

你可以处理ObservableCollection&lt;T&gt;CollectionChanged事件。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2015-09-29
  • 2017-03-09
  • 2021-10-02
  • 2014-06-06
  • 2018-04-20
  • 1970-01-01
相关资源
最近更新 更多