Search code examples
silverlightxamlwindows-phonegrid-layoutforeground

Setting foreground color for all TextBlocks in a Grid in one place in XAML (Silverlight, WP)


Let's say we have a construction like this:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <TextBlock Grid.Row="0" Grid.Column="0" />
    <TextBlock Grid.Row="0" Grid.Column="1" />

    <TextBlock Grid.Row="1" Grid.Column="0" />
    <TextBlock Grid.Row="1" Grid.Column="1" />

    <TextBlock Grid.Row="2" Grid.Column="0" />
    <TextBlock Grid.Row="2" Grid.Column="1" />
</Grid>

How can I set the foreground color for all textblocks in the grid as one setting?
Something similar to

<Grid Color="Red">
     ...
</Grid>

Solution

  • You can add a resources on the grid that sets all textBlock foreground's to red.

    <Grid>
        <Grid.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="Foreground" Value="Red"/>
            </Style>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
    
        <TextBlock Grid.Row="0" Grid.Column="0" >Good show</TextBlock>
        <TextBlock Grid.Row="0" Grid.Column="1" >Now the Foreground is red</TextBlock>
    
        <TextBlock Grid.Row="1" Grid.Column="0" />
        <TextBlock Grid.Row="1" Grid.Column="1" />
    
        <TextBlock Grid.Row="2" Grid.Column="0" />
        <TextBlock Grid.Row="2" Grid.Column="1" />
    </Grid>