R
R
rFczZZ2017-07-17 19:18:12
WPF
rFczZZ, 2017-07-17 19:18:12

Do I need INotifyCollectionChanged for collections if I don't use it?

Tell me, for example, for ItemsControl: if I inherit a collection from INotifyCollectionChanged - will it really carefully handle all NotifyCollectionChangedEventArgs.Action or can I send it empty, hoping that containers for already rendered elements will not be recreated?
Likewise, if I inherit the collection from INotifyPropertyChanged only - will the ItemsControl keep track of item references, creating containers for new objects only?
Of course, maybe I misunderstand the mechanism of building a "visual tree". Those. if the internal state of the collection has changed, everything needs to be deleted, new containers created and drawn. If the ItemsControl (for example) has a mechanism that compares references and does not recreate containers for old objects, then it turns out that it does not need INotifyCollectionChanged and does it really not look at it?
* added:
What happens if you put only IEnumerable there? Those. if the collection object itself is changed (in this case, there is no collection), but the elements remain the same, will there be a "blink" with clearing all internal states in the element containers?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sumor, 2017-07-18
@rFczZZ

If you want to test something, create a simple test project and have a look.
If your objects implement INotifyPropertyChanged, then even if they were bound to the ItemsControl using IEnumerable, the bound (Binding) properties in the template will be updated. They will not be completely recreated, but those properties that depend on the changed properties of your object will be updated. for example

<ItemsControl>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
         <TextBlock Text="{Binding Text}" Foreground="{Binding ForeColor}" />
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

Changing the Text property of your object will update the element's text. When the color changes, the color will be updated.
But if you put IEnumerable in ItemsSource, then changes to the collection itself are not tracked. neither adding nor removing. If your collection has changed, you need to reassign it again and then all visual elements will be recreated.
To track a change in a collection, it must implement INotifyCollectionChanged. You can take ObservableCollection<> collections as a basis - they already implement the necessary events.
Accordingly, if it is indicated in NotifyCollectionChanged that an element has been added, only it will be drawn. If the element is removed, it will be removed. The rest of the elements will not be affected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question