8

is there a way to specify something like this in WPF:

CSS:

#someSpan input { color: #f1f1f1; }
or
span input { color: #f1f1f1; }

meaning, i'd like to have all TextBlock elements within container follow x style, w/out having to apply the style to each textblock.

just to clarify, i need to do something like this in WPF.

i know about the BasedOn attribute of a style.. but that's not quite what i'm looking for here

looking for something like this

 <Style x:Key="FileItem"  TargetType="{x:Type #SomeContainer TextBlock}">

or maybe within SomeContainer, add a TextBlock style that will apply to all of its textblocks

H.B.
  • 166,899
  • 29
  • 327
  • 400
Sonic Soul
  • 23,855
  • 37
  • 130
  • 196

2 Answers2

10

You can do that, you just need to nest styles, e.g.

<Style TargetType="{x:Type Border}">
    <Style.Resources>
        <Style TargetType="{x:Type TextBox}">
            <!-- ... -->
        </Style>
    <Style.Resources>
</Style>

This allows you to style TextBoxes in Borders, elements however can only have one style applied to them, so having parallel "rules" is not going to work as well.

H.B.
  • 166,899
  • 29
  • 327
  • 400
6

Regarding the last part of your question, if you want to apply a style to all TextBlocks within a particular element, just put the Style within that elements resources:

<TextBlock /> <!-- unaffected -->

<Grid>
    <Grid.Resources>
        <Style TargetType="TextBlock">
            <!-- ... -->
        </Style>
    </Grid.Resources>

    <TextBlock /> <!-- will be styled -->
</Grid>

If you have your styles stored in a separate ResourceDictionary then you can "import" them all for a particular element by merging resource dictionaries:

<Grid>
    <Grid.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="/Resources/MyOtherStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Grid.Resources>

    <TextBlock /> <!-- will be styled -->
</Grid>
Steve Greatrex
  • 15,789
  • 5
  • 59
  • 73
  • good point.. though i have all my styles defined in a separate .xaml.. i suppose i can still point the above definition to a static resource... – Sonic Soul Nov 03 '11 at 12:59
  • 1
    yep, this pretty much does what i need.. however i still wish i didn't have to create local overrides for every element... – Sonic Soul Nov 03 '11 at 13:04
  • 1
    See my update - it's still not perfect, but you can use merged resource dictionaries to import a lot of styles at once – Steve Greatrex Nov 03 '11 at 13:10