WPF:如何在css中设置类的样式?

问题描述 投票:18回答:4

假设我有一个带有4个边框的UserControl:

<Border />
<Border />
<Border />
<Border />

现在在我的资源中,我可以去:

<Style TargetType="{x:Type Border}">
  ... change some properties here
</Style>

现在这一切都很好,但它将针对我的UserControl中的所有边框。但是,如果我只想针对它们的一部分呢?

我想去:

<Border Class="Type1" />
<Border Class="Type1" />
<Border />
<Border />

然后去:

<Style TargetType="{x:Type Border}" TargetClass="Type1">
  ... change some properties here
</Style>

但这显然不存在,还有其他方法可以实现我追求的目标吗?谢谢

c# wpf xaml
4个回答
16
投票

虽然语法不像CSS那样干净,但它更具体。

为了建立你的榜样,你要找的是:

<Border Style="{StaticResource Type1}" />
<Border Style="{StaticResource Type1}" />
<Border />
<Border />

然后去:

<Style TargetType="{x:Type Border}" x:Key="Type1">
  ... change some properties here
</Style>

请记住,WPF样式实际上并不像CSS那样级联。

更详细的造型参考:https://web.archive.org/web/20141210000517/http://dotnetslackers.com/articles/wpf/StylesResourcesAndControlTemplatesInWPF.aspx


10
投票

我发现大多数人都不知道的是WPF在Style.Resources中嵌套样式的能力。例如:

<!-- Define a new style for Borders called InfoBox, that will have a red background, 
     and further override all buttons within it to have Yellow Text.  An extra style,
     "Strawberry" is also defined, that lets specific buttons be selected to be styled
     as Green FG on DarkRed BG -->
<Style TargetType="{x:Type Border}" x:Key="InfoBox">
  <Setter Property="Background" Value="Red"/>
  <Style.Resources>
    <Style TargetType="{x:Type Button}">
      <Setter Property="Foreground" Value="DarkYellow"/>
    </Style>
    <Style TargetType="{x:Type Button}" x:Key="Strawberry">
      <Setter Property="Foreground" Value="Green"/>
      <Setter Property="Background" Value="DarkRed"/>
    </Style>
  </Style.Resources>
</Style>

...

<Border Style="{DynamicResource InfoBox}">
   <StackPanel>
     <Button Content="I am a banana!"/>
     <Button Style="{DynamicResource Strawberry}" Content="I am red!"/>
   </StackPanel>
</Border>

虽然与CSS不完全相同(标准伪选择器没有太多支持),但这为您提供了巨大的功能和灵活性。通过巧妙地使用ItemsControls来结合这一点,你可以做一些很棒的事情。


2
投票
<Style x:Key="styleKey" TargetType="{x:Type Border}">
  ... change some properties here
</Style>

<Border Style="{StaticResource styleKey}"

1
投票

您可以使用x:key和Border的StaticResource(或DynamicResource)属性直接在<Border>上设置样式。如果您想在运行时更改样式,那么您应该倾向于使用DynamicResource而不是StaticResource。

<Style x:Key="something" TargetType="{x:Type Border}">
</Style>

<Border style="{StaticResource something}"/>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.