WPF - Best way to remove an item from the ItemsSource

前端 未结 4 536
日久生厌
日久生厌 2020-12-17 02:22

I\'m writing a custom ItemsControl (a tabbed document container), where each item (tab) can remove itself from the UI when the user closes it. However, I can\'t

4条回答
  •  失恋的感觉
    2020-12-17 02:34

    As you've found, your ItemsControl doesn't have intrinsic knowledge of the items being bound - those types are provided by consumers of your control. And you can't modify the collection directly because it may be data-bound.

    The trick is to ensure each item is wrapped by a custom class (item container) of your choosing. Your ItemsControl you can provide this in the GetContainerForItemOverride method.

    From there, you can define properties on your custom item container that you then bind to in your default template. For example, you could have a property called State that changes between Docked, Floating, and Closed. Your template would use this property to determine how - and whether - to show the item.

    So you will not actually be changing the underlying data source at all. Instead, you will change a control-specific layer on top of the underlying data items that give you the info you need to implement your control.

提交回复
热议问题