WPF: changing background behind tabs for TabControl when tabItems are centered

So, I want the tabs on my tabs to be horizontally centered. I also want to change the background behind the tabs. I found the answer for both of these things:

This explains what I want to do for the background and give a solution

This explains how to center tabItems.

The problem is that they both work perfectly separately, but when combined, they do not work. The tabItems are centered in order, but the background color is not the color I specify.

eg. The code:

<TabControl> <TabControl.Resources> <Style TargetType="{x:Type TabPanel}"> <Setter Property="HorizontalAlignment" Value="Center" /> <Setter Property="Background" Value="Red" /> </Style> </TabControl.Resources> <TabItem Header="Test 1" /> <TabItem Header="Test 2" /> <TabItem Header="Test 3" /> <TabItem Header="Test 4" /> </TabControl> 

reference

+8
c # wpf tabcontrol
source share
1 answer

Oh, what a nightmare that was supposed to find the problem. The problem is with the default template that uses tabcontrol.

DefaultTemplate for TabControl

TabPanel itself, when it is configured for something other than stretching, does not fill up more than you need in the grid. That is why the background did not appear.

Another problem was that the ContentPanel background was associated with the TabControl template. Therefore, after digging, I found that I can override the grid style that makes up the tabcontrol with the background, and it will only fill the first line of the grid, since the background of the second line was attached to the template.

Hope it makes sense that you can see what I get by looking at the default template.

Here is the actual code for its operation

 <TabControl> <TabControl.Resources> <Style TargetType="{x:Type Grid}"> <Setter Property="Background" Value="Red"/> </Style> <Style TargetType="{x:Type TabPanel}"> <Setter Property="HorizontalAlignment" Value="Center"/> </Style> </TabControl.Resources> <TabItem Header="Test 1"/> <TabItem Header="Test 2"/> <TabItem Header="Test 3"/> <TabItem Header="Test 4"/> </TabControl> 

And this is what it should look like enter image description here

+9
source share

All Articles