tags:

views:

25

answers:

2

I am trying to synchronize the selected tab item of a WPF tab control with the last item that was added.

Since there is no such property as e.g. IsSynchedWithLastAddedItem, I am trying to detect when an item was added in order to point the SelectedItem at the last added one.

I cannot find the event that gets raised - either on the tab control or its Items, when a TabItem was added.

I am sure something like it must exist though, so I hope someone can help me out.

+2  A: 
var view=CollectionViewSource.GetDefaultView(m_tabControl.ItemsSource);
view.CollectionChanged+=(o,e)=>{/*Here your code*/};

If you work directly with the Items-collection, the same technique will work also. Get the default CollectionViewSource for this collection.

var view=CollectionViewSource.GetDefaultView(m_tabControl.Items);
view.CollectionChanged+=(o,e)=>{/*Here your code*/};

As Timores wrote, for the m_tabControl.Items-property, you can attach a handler directly. The same is also true for most ItemsSource-references, but there you have to check yourself for the INotifyCollectionChanged-interface.

I have not tested it. Make a comment if it does not work.

HCL
Thanks, the second option worked perfect.The first one will work only once the ItemsSource was set, so you can't use it in the constructor of the view.The reason is that at that point the ItemsSource is still null and thus the default view is also.
Thorsten Lorenz
A: 

The Items collection is of type ItemCollection, which derives from CollectionView which implements INotifyCollectionChanged. So you could listen to CollectionChanged and get to know when an item is added.

Don't know how to do that in XAML, though.

Timores