WPF:如何像CSS一样设置类的样式?
假设我有一个带有 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>
但这显然不存在,还有其他方法可以实现我所追求的吗? 谢谢
Let's say I have a UserControl with 4 Borders:
<Border />
<Border />
<Border />
<Border />
Now in my Resources I can go:
<Style TargetType="{x:Type Border}">
... change some properties here
</Style>
Now this is all good, but it will target all borders in my UserControl.
But what if I just want to target a subset of them?
I'd like to go:
<Border Class="Type1" />
<Border Class="Type1" />
<Border />
<Border />
And then go:
<Style TargetType="{x:Type Border}" TargetClass="Type1">
... change some properties here
</Style>
But this obviously doesn't exist, is there some other way I can achieve what I'm after?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然语法不像 CSS 那样清晰,但它更加具体。
为了构建您的示例,您需要的是:
然后继续:
请记住,WPF 样式实际上并不像 CSS 那样级联。
更详细的造型参考:
https://web.archive.org /web/20141210000517/http://dotnetslackers.com/articles/wpf/StylesResourcesAndControlTemplatesInWPF.aspx
Though the syntax isn't quite as clean as in CSS, it is a lot more specific.
To build on your example, what you're looking for is:
And then go:
Remember that WPF styles don't actually cascade like CSS does.
A more detailed styling reference:
https://web.archive.org/web/20141210000517/http://dotnetslackers.com/articles/wpf/StylesResourcesAndControlTemplatesInWPF.aspx
我发现大多数人都没有意识到 WPF 在 Style.Resources 中嵌套样式的能力。例如:
虽然与 CSS 不完全相同(对标准伪选择器没有太多支持),但这为您提供了巨大的功能和灵活性。将此与 ItemsControls 的熟练使用相结合,您可以做一些伟大的事情。
Something that I find most people are not aware of is WPF's ability to nest Styles within Style.Resources. For example:
While not exactly the same as CSS (There isn't much support for standard pseudo-selectors), this gives you a huge amount of power and flexibility. Couple this with skillful use of ItemsControls and you can do some great things.
您可以使用 x:key 和 Border 的 StaticResource(或 DynamicResource)属性直接在
上设置样式。如果您想在运行时更改样式,那么您应该倾向于使用 DynamicResource 而不是 StaticResource。you can set the style directly on the
<Border>
using an x:key and the StaticResource (or DynamicResource) property of the Border. if you would like to change the style at runtime, then you should lean towards using the DynamicResource over the StaticResource.和
and