Such a dilemma: I have a "ItemsSource" in my control. IEnumerable DependencyProperty . An ObservableCollection<T> attached to it. I need to add / remove items from the outside into the bound collection. However, I do not know which collection is bound, I have access only to the property of the element, and IEnumerable does not imply the Clear or Add functions.

What can be done here?

  • You can try to lead to ICollection<T> , if you know T , or even immediately to ObservableCollection<T> . So many classes working with WPF do. - Monk
  • one
    Nothing. If you declare an IEnumerable property, the client has the right to write there any implementation, including those that do not support adding elements. If you need the ability to add elements, declare a type that supports this, for example IList . - Andrey NOP
  • one
    In general, see, for example, how ItemsControl is implemented - it also implements the separate Items property. Well, you can see how it is done in DataGrid - if a collection is attached to it that does not allow adding elements, then this functionality is disabled, you can go along this path - Andrey NOP
  • Yes, maybe I did not specify. I will always have an ObservableCollection . I just don’t know the type of the element, so I made a generic IEnumerable . - Puro

1 answer 1

Thank you @ AndreyNOP. Since IEnumerable does not support changing the collection, I changed the property type to IList . In my situation, this did not cause additional problems.