Wpf 如何通过Datatemplate更改控件样式中TextBlock的前景?

Wpf 如何通过Datatemplate更改控件样式中TextBlock的前景?,wpf,Wpf,我有一个控件输入字段的样式,代码xaml: <Style TargetType="{x:Type c:InputField}" BasedOn="{StaticResource TextBoxStyle}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type c:InputField}"&

我有一个控件
输入字段
的样式,代码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.
Properties
ItemTextBox
。我现在的问题是:“如何仅为该数据模板更改
InputField
TextBlock
前景
,这意味着我不能为所有窗口更改
TextBlock
前景
颜色,而只能为该
DataTemplate
?”
谢谢你的帮助

在您的
样式中,使用
Setter
元素声明前景,默认情况下,它是您的
InputFieldLabelForegroundBrush

<Style TargetType="{x:Type c:InputField}" BasedOn="{StaticResource TextBoxStyle}">
    <Setter Property="Foreground" Value="{DynamicResource InputFieldLabelForegroundBrush}"/>
    ...
</Style>
现在,在
数据模板
中需要做的就是在
文本块
上显式设置
前台
,剩下的工作将由
模板绑定
完成

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


也许不要直接在
文本块上设置
前景
,而是尝试在整个控件本身上设置它。我认为,
前台
会向下延伸到子元素。如果没有,可以使用模板绑定将其绑定到
Textblock
。然后您可以在数据模板中修改控件本身的属性。@Xavier,谢谢您的关注。我试试看,谢谢你的答复。但是所有窗口的前景色都是红色,因为有很多地方使用“g:ItemTextBox”。我只想更改“v:DetailSettings”的DataTemplate中的前台。创建一个新的
DataTemplate
(供您的v:DetailSettings使用),并给它一个x:Key。在
ItemsControl
中,只需将
itemstemplate
设置为
{StaticResource whateverYouCalledIt}
。这将强制ItemsControl使用不同的
DataTemplate
<Style TargetType="{x:Type c:InputField}" BasedOn="{StaticResource TextBoxStyle}">
    <Setter Property="Foreground" Value="{DynamicResource InputFieldLabelForegroundBrush}"/>
    ...
</Style>
<TextBlock Foreground="{TemplateBinding Foreground}" ... />
<c:InputField Label="{Binding Caption}" Text="{Binding Text}" Foreground="Red"/>