Luke Le
Luke Le

Reputation: 778

How to change Foreground of TextBlock in a style of a control through Datatemplate?

I have a style for control InputField, code xaml:

    <Style TargetType="{x:Type c:InputField}" BasedOn="{StaticResource TextBoxStyle}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type c:InputField}">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="auto"></RowDefinition>
                        <RowDefinition></RowDefinition>
                    </Grid.RowDefinitions>
                    <TextBlock Text="{Binding Label, RelativeSource={RelativeSource TemplatedParent}}" Grid.Row="0" 
                           Foreground="{DynamicResource InputFieldLabelForegroundBrush}" Name="Label" 
                           />
                    <Border Grid.Row="1"
                          Background="{TemplateBinding Background}"
                          BorderBrush="{TemplateBinding BorderBrush}"
                          BorderThickness="{TemplateBinding BorderThickness}" >
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
Foreground="{DynamicResource InputFieldLabelForegroundBrush}" specification foreground of TextBlock.

I use this control InputField in a DataTemplate:

<DataTemplate DataType="{x:Type g:ItemTextBox}">        
    <c:InputField Label="{Binding Caption}" Text="{Binding Text}"/>
</DataTemplate>

It work fine with TextBlock has Foreground is InputFieldLabelForegroundBrush. I use ItemTextBox a lot of places. One of them is:

<DataTemplate DataType="{x:Type v:DetailSettings}">
    <Border Width="290" Background="{DynamicResource DetailSettingsBackgroundBrush}">
        <Grid>
            <ItemsControl ItemsSource="{Binding Properties}"/>
        </Grid>
    </Border>
</DataTemplate>

Properties is ItemTextBox. My problem now is: "How to change Foreground of TextBlock in InputField only for this DataTemplate, that mean I must not change the Foreground color of TextBlock for all windows, but only for this DataTemplate?" Thanks for help me !!!

Upvotes: 1

Views: 659

Answers (1)

Mike Eason
Mike Eason

Reputation: 9723

In your Style, use the Setter element to declare the foreground which by default, is your InputFieldLabelForegroundBrush.

<Style TargetType="{x:Type c:InputField}" BasedOn="{StaticResource TextBoxStyle}">
    <Setter Property="Foreground" Value="{DynamicResource InputFieldLabelForegroundBrush}"/>
    ...
</Style>

In the Template for your Style, you can then reference this by using a TemplateBinding.

<TextBlock Foreground="{TemplateBinding Foreground}" ... />

Now all you need to do in your DataTemplate, is explicitly set the Foreground on the TextBlock, and the TemplateBinding will do the rest.

<c:InputField Label="{Binding Caption}" Text="{Binding Text}" Foreground="Red"/>

Upvotes: 1

Related Questions