WPF 样式基于当前上下文中的父样式

red*_*pes 1 wpf styles basedon

比如说,我有一个TextBox“TextBoxStyleBase”的默认样式。然后,我定义一个DataGrid样式,该样式具有TextBox基于该基本样式的自己的样式,并定义另一个边框颜色。

在 a 内部的某个地方,DataGrid我想定义另一种TextBox样式,但继承于 style 中定义的样式DataGrid

有没有办法使样式继承当前为当前“上下文”中的特定控件定义的样式?

编辑:

为了更清楚地说明,这是我所拥有的:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

BasedOn = '???' 中要放入什么 这样文本就会以 FontSize 20 的形式显示,但悬停时会显示为粗体。

mm8*_*mm8 6

您不能在同一个 .txt 文件中添加两个Styles具有相同密钥的文件ResourceDictionary。因此,如果您已经为特定类型定义了一个Style没有x:Keyin a 的隐式ResourceDictionary,则无法将另一个类型添加到同一类型中ResourceDictionary

否则,您应该能够基于Style范围内的默认样式,如下所示:

<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
    <Style.Triggers>

    </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)