Search code examples
wpfxamldata-bindingtabcontroltabitem

Change Opaticy of Tab Item In an Items Control


I have a data bound tab control:

<TabControl ItemsSource="{Binding Products}" Name="ProductsTabControl">
  <TabControl.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Name}"/>
    </DataTemplate>
  </TabControl.ItemTemplate>
</TabControl>

This control is showing one tab per product, however I would like to make the tabs of discontinued products semi-transparent (i.e. set their opacity to 0.2). How can I change the opacity property of the tabitem when the item is being auto generated. I know I could use a style to change them all, but I only want to change those which are discontinued.


Solution

  • In ItemsContainerStyle for TabControl, create a DataTrigger where you bind to your property (e.g IsDiscontinued) and set the Opacity from there

    <TabControl ItemsSource="{Binding Products}" Name="ProductsTabControl">
        <TabControl.ItemContainerStyle>
            <Style TargetType="TabItem">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsDiscontinued}" Value="True">
                        <Setter Property="Opacity" Value="0.2"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TabControl.ItemContainerStyle>
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
    </TabControl>
    

    Update

    If you want to make the Content of the discontinued tabs semi-transparent you can do the same thing, but in the DataTemplate

    <TabControl ItemsSource="{Binding Products}" Name="ProductsTabControl">
        <TabControl.Resources>
            <DataTemplate DataType="{x:Type local:Product}">
                <Border Name="bg" BorderBrush="Black" BorderThickness="1">
                    <TextBlock Text="{Binding Name}"/>
                </Border>
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding IsDiscontinued}" Value="True">
                        <Setter TargetName="bg" Property="Opacity" Value="0.2"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </TabControl.Resources>
        <!--...-->
    </TabControl>