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

for*_*yez 18 c# wpf xaml

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

<Border />
<Border />
<Border />
<Border />
Run Code Online (Sandbox Code Playgroud)

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

<Style TargetType="{x:Type Border}">
  ... change some properties here
</Style>
Run Code Online (Sandbox Code Playgroud)

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

我想去:

<Border Class="Type1" />
<Border Class="Type1" />
<Border />
<Border />
Run Code Online (Sandbox Code Playgroud)

然后去:

<Style TargetType="{x:Type Border}" TargetClass="Type1">
  ... change some properties here
</Style>
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*rey 16

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

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

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

然后去:

<Style TargetType="{x:Type Border}" x:Key="Type1">
  ... change some properties here
</Style>
Run Code Online (Sandbox Code Playgroud)

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

更详细的样式参考:http: //dotnetslackers.com/articles/wpf/StylesResourcesAndControlTemplatesInWPF.aspx

  • Wayback 机器来救援! (3认同)

Arm*_*age 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>
Run Code Online (Sandbox Code Playgroud)

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


Mua*_*Dib 2

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

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

<Border style="{StaticResource something}"/>
Run Code Online (Sandbox Code Playgroud)