user2088807
user2088807

Reputation: 1408

Tabitem template get displayindex?

I want to create a style for my tabitems with the following properties : - the first tabitem will set a corner radius on the left corners - the last tabitem will set a corner radius on the right corners

Result expected :enter image description here

Problem 1 : So I need to be able to get the index of the current tabitem in the template (and also the number of tabitems in the tabcontrol.

I'd like to be able to do it in one style. I'm currently doing it with 3 styles (one for the first, one for the last and one for the others) but in my application I often have to hide one or two tabitems so I need to check if I have to set a new style in code which is not really useful.

Problem 2 : I'd like to change the style of all the tabitems before the current selected tabitem.

Is this possible using only one style ?

Thank you

Upvotes: 0

Views: 112

Answers (1)

Xi Sigma
Xi Sigma

Reputation: 2372

The 3 styles part is alright, what you are missing is a StyleSelector that will select the style based on the ItemIndex

public class TabItemStyleSelector : StyleSelector
    {
        public override Style SelectStyle(object item, DependencyObject container)
        {
            var itemsControl = ItemsControl.ItemsControlFromItemContainer(container);
            var itemIndex = itemsControl.ItemContainerGenerator.IndexFromContainer(container);

            //first index
            if(itemIndex == 0)
            {
                return (Style)itemsControl.FindResource("FirstTabItemItemStyle");
            }
            //last index
            if (itemIndex == itemsControl.Items.Count - 1)
            {
                return (Style)itemsControl.FindResource("LastTabItemItemStyle");
            }

            //other indecies
            return (Style)itemsControl.FindResource("OtherTabItemItemStyle");

            //return base.SelectStyle(item, container); return this if OtherTabItemItemStyle does not exist
        }
    }

Add it to your resuources

<Window.Resources>
        <local:TabItemStyleSelector x:Key="TabItemStyleSelector" />
 </Window.Resources>

and use it in your TabControl as:

 <TabControl ItemsSource="{Binding Items}" ItemContainerStyleSelector="{StaticResource TabItemStyleSelector}">
</TabControl>

note the above Selector works for any ItemsControl not just TabControl

Upvotes: 2

Related Questions