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"/>