Override typed textblock style for contentpresenter in WPF

这一生的挚爱 提交于 2019-12-24 02:48:09

问题


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 when 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"?


回答1:


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!



来源:https://stackoverflow.com/questions/5381018/override-typed-textblock-style-for-contentpresenter-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!