在WPF中,如何防止我的样式被覆盖?

Tim*_*uri 8 wpf styling

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

在我的WPF应用程序中,如果我希望所有TextBox都具有"绿色"背景,我可以在我的Application.Resources中轻松设置它.

<Style TargetType="TextBox">
 <Setter Property="Background" Value="Green" />
</Style>
Run Code Online (Sandbox Code Playgroud)

完美地工作 ......(谢谢你WPF).但是,如果我在我的应用程序中的某个地方有一个TextBox,我想要添加更多样式 ......我失去了我的绿色背景.

例:

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

当鼠标结束时,TextBox将正确地具有红色前景,但绿色背景完全丢失.

所以,问题是:我如何告诉WPF不要完全消除所有来自上面的样式,因为我有一个简单的,非冲突的,这么小的风格添加到控件的某个地方?

Guy*_*uck 11

您可以使用Style声明中的"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>
Run Code Online (Sandbox Code Playgroud)

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

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

<Style BasedOn="{StaticResource MyNamedStyle}" >
</Style>
Run Code Online (Sandbox Code Playgroud)