【问题标题】:WPF Style BasedOn parent Style in current context当前上下文中的 WPF Style BasedOn 父样式
【发布时间】:2017-10-19 07:24:21
【问题描述】:

说,我有一个TextBox'TextBoxStyleBase' 的默认样式。 然后我定义一个DataGrid 样式,它有一个自己的TextBox 样式BasedOn 基础样式,定义另一个边框颜色。

DataGrid 内的某个地方,我想定义另一个TextBox 样式,但继承自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>

在 BasedOn = '???' 中添加什么以便文本以 FontSize 20 显示,但如果悬停,则显示为粗体。

【问题讨论】:

    标签: wpf styles basedon


    【解决方案1】:

    您不能在同一个ResourceDictionary 中添加两个具有相同密钥的Styles。因此,如果您已经在 ResourceDictionary 中为特定类型定义了一个隐含的 Style 而没有 x:Key,则不能将另一个添加到同一个 ResourceDictionary

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

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

    【讨论】:

      【解决方案2】:

      请在数据网格中使用以下文本框:

      <Style TargetType="TextBox" BasedOn="{StaticResource <your style name>}">
      

      PS:在你的情况下是 TextBoxStyleBase。

      【讨论】:

      • 我想你理解错了我的问题,请参考我的说明
      • 你为什么不给它一个钥匙,然后在你需要的地方使用它?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      相关资源
      最近更新 更多