开发者

WPF: Problem applying style to custom TabItem Header through ControlTemplate and ContentPresenter.Resources

开发者 https://www.devze.com 2023-03-09 13:45 出处:网络
I am trying to write my own control template for a TabItem Header, and have got the basic layout to work but now I wish to apply styling to the content of the Header, for example to manipulate the siz

I am trying to write my own control template for a TabItem Header, and have got the basic layout to work but now I wish to apply styling to the content of the Header, for example to manipulate the size and font of a textblock.

In order to test this, I have put an ellipse in the tabitem header and am attempting to fill that ellipse with the Gold brush through styling. However, it is not working. The ellipse is present, and the control template is being applied, but the fill of the ellipse is not Gold. The style within the ContentPresenter.Resources is being ignored (and Resharper has even greyed it out to prove that). Any ideas what I'm doing wrong? Thanks.

Here is the code:

    <TabItem>
    <TabItem.Template>
        <ControlTemplate x:Name="theTabItemControlTemplate" TargetType="{x:Type TabItem}">
            &l开发者_如何学编程t;Border BorderBrush="DarkBlue" BorderThickness="10">
                <Grid>
                    <ContentPresenter ContentSource="Header" RecognizesAccessKey="True">
                        <ContentPresenter.Resources>
                            <Style TargetType="{x:Type Ellipse}">
                                <Setter Property="Ellipse.Fill" Value="Gold"/>
                            </Style>
                        </ContentPresenter.Resources>
                    </ContentPresenter>
                </Grid>
            </Border>
        </ControlTemplate>
    </TabItem.Template>
    <TabItem.Header>
        <Ellipse Stroke="Black" StrokeThickness="2" Width="100" Height="30" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
    </TabItem.Header>
</TabItem>


Move your style one level upper.ie,move it to ControlTemplate.Resources and it will work fine.I am quite not sure why the code in the question does not work.It may be because the controls in the contentpresenter is already built by the time the style is encountered.

<ControlTemplate x:Name="theTabItemControlTemplate" TargetType="{x:Type TabItem}">
            <ControlTemplate.Resources>
                <Style TargetType="{x:Type Ellipse}">
                    <Setter Property="Fill" Value="Red"/>
                </Style>
            </ControlTemplate.Resources>
            <Border BorderBrush="DarkBlue" BorderThickness="10">
        <Grid>
            <ContentPresenter ContentSource="Header" RecognizesAccessKey="True">

            </ContentPresenter>
        </Grid>
    </Border>
</ControlTemplate>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号