WPF 样式基于当前上下文中的父样式 [英] WPF Style BasedOn parent Style in current context
问题描述
比如说,我有一个 TextBox
'TextBoxStyleBase' 的默认样式.然后我定义了一个 DataGrid
样式,它有一个自己的 TextBox
样式基于那个 Base-style,定义另一个边框颜色.
Say, I have a default style for a TextBox
'TextBoxStyleBase'.
I then define a DataGrid
style which has an own TextBox
style BasedOn that Base-style, defining another Border Color.
在 DataGrid
内的某个地方,我想定义另一种 TextBox
样式,但继承自 DataGrid
样式中定义的样式.
In some place inside a DataGrid
I want to define another TextBox
style but inherit from the one defined in DataGrid
style.
有没有办法让样式继承当前为当前上下文"中的特定控件定义的样式?
Is there a way to make a style inherit from the style that is currently defined for a specific control in the current 'context'?
为了更清楚,这是我所拥有的:
To make it more clear, here's what I have:
<!-- explicit style for all TextBoxes -->
<Style TargetType="{x:Type TextBox}" x:Key="TextStyle">
<Setter Property="FontSize" Value="16"/>
</Style>
<!-- implicit style for all TextBoxes -->
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource TextStyle}"/>
<!-- DataGrid style changing inner TextBox style -->
<Style TargetType="{x:Type DataGrid}">
<Style.Resources>
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource TextStyle}">
<Setter Property="FontSize" Value="20"/>
</Style>
<!-- since TextBox has defined implicit style this would be equivalent to -->
<!--<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="FontSize" Value="20"/>
</Style>-->
</Style.Resources>
</Style>
<Control>
<DataGrid>
<Row>
<TextBox/> <!-- should show as defined in DataGrid style -->
</Row>
<Row>
<Row.Resources>
<Style TargetType="{x:Type TextBox}" BasedOn=" ??? ">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
</Trigger>
</Style.Triggers>
</Style>
</Row.Resources>
<TextBox/> <!-- should show with additional trigger -->
</Row>
</DataGrid>
</Control>
在 BasedOn = '???' 中放什么以便文本以 FontSize 20 显示,但如果悬停则显示为粗体.
What to put in BasedOn = '???' so that the text shows up in FontSize 20 but Bold if hovered.
推荐答案
不能在同一个 ResourceDictionary
中添加两个具有相同键的 Styles
.因此,如果您已经在 ResourceDictionary
中为特定类型定义了一个没有 x:Key
的隐式 Style
,则不能再添加一个到相同的ResourceDictionary
.
You cannot add two Styles
with the same key inside the same ResourceDictionary
. So if you already have defined an implicit Style
without an x:Key
in a ResourceDictionary
for a specific type, you cannot add another one to the same ResourceDictionary
.
否则,您应该能够将 Style
基于范围内的默认样式,如下所示:
Otherwise you should be able to base a Style
on the default style that is in scope like this:
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Triggers>
</Style.Triggers>
</Style>
这篇关于WPF 样式基于当前上下文中的父样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!