11

请不要陷入我的例子中,只是为了这个问题而忍受我:

在我的 WPF 应用程序中,如果我希望所有 TextBox 都具有“绿色”背景,我会在 Application.Resources 中轻松地设置它。

<Style TargetType="TextBox">
 <Setter Property="Background" Value="Green" />
</Style>

这非常有效......(谢谢WPF)。但是,如果我在我的应用程序的某个地方有一个文本框,我想在其中添加更多样式……我失去了我的绿色背景。

例子:

<TextBox>
 <TextBox.Style>
  <Style>
   <Style.Triggers>
    <Trigger Property="TextBox.IsMouseOver" Value="True">
     <Setter Property="TextBox.Foreground" Value="Red" />
    </Trigger>
  </Style.Triggers>
  </Style>
 </TextBox.Style>
</TextBox>

当鼠标悬停时,该 TextBox 将正确地具有红色前景,但绿色背景完全丢失。

所以,问题是:我如何告诉 WPF 不要仅仅因为我在某个地方添加了一个简单的、不冲突的、如此微小的样式而完全清除来自上面的所有样式?

4

1 回答 1

13

您可以在样式声明中使用“BasedOn”继承已经覆盖的样式。

在你的第二种风格的声明中,试试这个:

<TextBox>
 <TextBox.Style>
  <Style BasedOn="{StaticResource {x:Type TextBox}}">
   <Style.Triggers>
    <Trigger Property="TextBox.IsMouseOver" Value="True">
     <Setter Property="TextBox.Foreground" Value="Red" />
    </Trigger>
  </Style.Triggers>
  </Style>
 </TextBox.Style>
</TextBox>

您还可以将样式基于命名样式,

<Style x:Key=MyNamedStyle>
</Style>

<Style BasedOn="{StaticResource MyNamedStyle}" >
</Style>
于 2009-10-19T13:55:05.083 回答