1

I have 2 classes:

class MultiSwitch : ListBox
{
    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return item is MultiSwitchItem;
    }
    protected override DependencyObject GetContainerForItemOverride( )
    {
        return new MultiSwitchItem( );
    }

}

class MultiSwitchItem : ListBoxItem {...}

Basically, I want to place items depending on items count. So I subscribed to collection changed event and i'm trying to recieve MultiSwitchItem from Items collection. I found out that Items collection doesn't contain MultiSwitchItems. Then I found solution that looks like that:

    private void RearrangeItems(
        object sender,
        NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
    {
        foreach (var item in Items)
        {
            MultiSwitchItem item2 = ItemContainerGenerator.ContainerFromItem(item) as MultiSwitchItem;
            ...
        }
    }

But item2 is always null. What am I doing wrong?

EDIT Ok, I have a little progress with that. This issue appears only when control is initialized (so I think, wrappers for items are created not instantly). So the question now: how to force creating of MultiSwitchItems, or how to iterate over items AFTER wrappers was created?

  • If you want to rearrange the items, why don't you use a CollectionView? Another solution is to write your own panel. Or if you insist on doing it that way, you can try the OnLoaded event, or the ItemContainerGenerator events to start your rearranging later. – dowhilefor Apr 26 '13 at 14:49
  • @dowhilefor I think that it's more easy to implement this logic right in my container... Anyway, I subscribed to Loaded event and it works! Thanks for help! – Konstantin Vasilev Apr 26 '13 at 15:03

1 Answers1

0

instead of this

ItemContainerGenerator.ContainerFromItem(item as TextBlock)

do this

ItemContainerGenerator.ContainerFromItem(item)

item wont be a TextBlock, it will be the underlying data item

Dean Chalk
  • 20,076
  • 6
  • 59
  • 90