Home > other >  WinUI: How to reduce duplicate code when using lightweight styling?
WinUI: How to reduce duplicate code when using lightweight styling?

Time:03-03

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.

CodePudding user response:

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

CodePudding user response:

Instead of trying to style a built-in Button, you could consider creating a custom Button 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:

<!-- 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>

...and change the base class of the code-behind class accordingly:

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

You could then create instances of this Button in any other view as usual, e.g.:

<local:MyCustomButton Content="Click me!" />
<local:MyCustomButton Content="Another button..." />
  • Related