WinUI:使用轻量级样式时如何减少重复代码?
我正在使用轻量级样式 设置按钮样式:
<Button ...>
<Button.Resources>
<SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="#48B2E9"/>
<SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="Black"/>
...
</Button.Resources>
</Button>
我想将此样式应用于多个(但不是全部)按钮。
目前,我需要将这些
复制并粘贴到我想要设计样式的每个按钮。
有没有办法避免这种重复?
我尝试创建一种样式,但不知道如何在样式中设置资源。
我想我可以创建一个控制模板,但这似乎很严厉。
I am using lightweight styling to style a button:
<Button ...>
<Button.Resources>
<SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="#48B2E9"/>
<SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="Black"/>
...
</Button.Resources>
</Button>
I would like to apply this styling to multiple (but not all) buttons.
Currently I need to copy and paste these <Button.Resources>
to every button I want styled.
Is there a way to avoid this duplication?
I tried creating a style but couldn't figure out how to set resources in a style.
I guess I could create a control template, but that seems heavy handed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
抱歉,造成误解,
您无法在样式定义上设置资源。
因此,您必须向按钮添加附加的 DependencyProperty,然后将其设置在样式定义上
,请参阅 这个
Sorry About Misundrstanding
you cannot set Resources on a style definition.
so you must add a attached DependencyProperty to button and then set it on a style definition
see this
您可以考虑创建一个始终应用资源的自定义
Button
控件,而不是尝试设置内置Button
的样式。在 Visual Studio 中将
UserControl
添加到项目(项目 -> 添加新项 -> 用户控件),并将 XAML 文件的内容替换为如下内容:...并更改基础相应地,代码隐藏类的类:
然后您可以照常在任何其他视图中创建此
Button
的实例,例如:Instead of trying to style a built-in
Button
, you could consider creating a customButton
control which always have the resources applied to it.Add a
UserControl
to the project (Project->Add New Item->User Control) in Visual Studio and replace the contents of the XAML file with something like this:...and change the base class of the code-behind class accordingly:
You could then create instances of this
Button
in any other view as usual, e.g.: