1

我正在使用轻量级样式来设置按钮样式:

<Button ...>
    <Button.Resources>
        <SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="#48B2E9"/>
        <SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="Black"/>
        ...
    </Button.Resources>
</Button>

我想将此样式应用于多个(但不是全部)按钮。

目前我需要将这些复制并粘贴<Button.Resources>到我想要设置样式的每个按钮上。

有没有办法避免这种重复?

我尝试创建一种样式,但不知道如何在样式中设置资源。

我想我可以创建一个控制模板,但这似乎很重。

4

2 回答 2

1

Button您可以考虑创建一个Button始终应用资源的自定义控件,而不是尝试设置内置的样式。

在 Visual Studio 中向项目(项目->添加新项->用户控件)添加一个UserControl,并将 XAML 文件的内容替换为以下内容:

<!-- MyCustomButton.xaml -->
<Button
    x:Class="WinUIApp.MyCustomButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Button.Resources>
        <SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="#48B2E9"/>
        <SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="Black"/>
    </Button.Resources>
</Button>

...并相应地更改代码隐藏类的基类:

// MyCustomButton.xaml.cs
public sealed partial class MyCustomButton : Button
{
    public MyCustomButton()
    {
        this.InitializeComponent();
    }
}

Button然后,您可以像往常一样在任何其他视图中创建此实例,例如:

<local:MyCustomButton Content="Click me!" />
<local:MyCustomButton Content="Another button..." />
于 2022-03-02T13:31:00.223 回答
0

对误会深表歉意

您不能在样式定义上设置资源。因此您必须将附加的 DependencyProperty 添加到按钮,然后将其设置为样式定义

看到这个

于 2022-03-01T20:45:38.080 回答