简体   繁体   中英

How do I get Count of parent collection from child?

I've got an ObservableCollection assigned to ItemsSource of a listbox. Listbox is using a DataTemplate which has a usercontrol in it which has items bound to each listboxitem's properties.

I have an up and down button on the usercontrol which moves an item up or down the list. The list is sorted by the property that I'm changing. Click up or down, the DisplayOrder property is changed, I'm using INotifyProperty to tell the ObservableCollection it needs to re-sort.

What is the best way for the usercontrol to get the item count so that I can disable the down button when an item reaches the bottom of the list. (The top is easy, I compare to 0)

listBox1.Items.Count ? this.Parent.Controls.Count?

I see two ways of handling this.

The first is to pass a handle of your collection to each of your items (when they get added to the collection) so that they can calculate if they are the first or last item themselves.

The other is to expose writable properties on your items, such as CanGoUp and CanGoDown , and your parent control becomes responsible for setting these properties properly. I prefer this solution because it decouples the behavior of your parent list, from the child items. Even though the up/down buttons are placed on your child items, it's really a functionality of the parent list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM