开发者

Override typed textblock style for contentpresenter in WPF

开发者 https://www.devze.com 2023-02-18 15:10 出处:网络
I have defined the Textblock style that are typed (as opposed to have a key value) so that it applies to all the textblocks.

I have defined the Textblock style that are typed (as opposed to have a key value) so that it applies to all the textblocks.

<Style TargetType="{x:Type TextBlock}">
        <Setter Property="FontFamily" Value="MyFancyFont"/>
        <Setter Property="FontSize" Value="13.333" />
        <Setter Property="Foreground" Value="Gray" />
</Style>

Now I have a, say, TreeViewItem, which I'd like to show as blue background and as white foreground against dark background whe开发者_开发技巧n it's selected.

<!--part of the treeviewitem template-->
<Trigger Property="IsSelected" Value="true">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Background" Value="Black"/>
</Trigger>

Defining a local style for the textblock doesn't work for the situation when the treeview item is selected, as the textblock in the item is still picking up the typed style.

Is there a good way to do this, while still keeping the textblock style as "Typed"?


this question may help you. It shows how to override an implicit style.

Ok, I understand your problem and I don't really have a direct solution, but anyways I will tell you how I handle such things:

You do know, that implicit styles are scoped, which means:

    <Grid>
        <Grid.Resources>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="FontFamily" Value="MyFancyFont"/>
            </Style>
        </Grid.Resources>
        <TextBlock>textblock with MyFancyFont</TextBlock>           
    </Grid>
    <TextBlock>textblock with normal font</TextBlock>

I usually try to avoid such an implicit style for TextBlock in the resources of my main window. Instead I might do:

<Application bunch="ofStuff">
    <Application.Resources>
        <Style TargetType="{x:Type TextBlock}" x:Key="TextBlockStandardStyle">
            <Setter Property="FontFamily" Value="MyFancyFont"/>
        </Style>
    </Application.Resources>
</Application>

then in subareas where that style can be implicit and doesn't cause any harm I will write:

    <Grid>
        <Grid.Resources>
            <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource TextBlockStandardStyle}"/>              
        </Grid.Resources>
        <TextBlock>textblock with MyFancyFont</TextBlock>           
    </Grid>

that way I can scope things how I want. Maybe this approach lets you skip the implicit style for the treeview so you can use your triggers!

0

精彩评论

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

关注公众号