Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascading styles in WPF (a la CSS)

Tags:

css

styling

wpf

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

like image 969
Sonic Soul Avatar asked Nov 03 '11 12:11

Sonic Soul


2 Answers

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.

like image 120
H.B. Avatar answered Sep 18 '22 13:09

H.B.


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>
like image 21
Steve Greatrex Avatar answered Sep 21 '22 13:09

Steve Greatrex