I would like to use C#, with no XAML, to have my Avalonia Button display a different background color while it is pressed. Creating Styles for :pointerover and :pressed work for changing the foreground color. But I can’t make it work for the background color for the :pressed pseudoclass. The foreground changes as I’ve specified, but the background turns to the same dark gray one sees when not using any style settings.
Here’s my code:
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Media;
using Avalonia.Styling;
class MainClass
{
public static void Main(string[] args) {
AppBuilder
.Configure<Application>()
.UsePlatformDetect()
.Start(AppMain, args);
}
public static void AppMain(Application app, string[] args)
{
app.Styles.Add(new Avalonia.Themes.Simple.SimpleTheme());
app.RequestedThemeVariant = Avalonia.Styling.ThemeVariant.Default;
var win = new Window
{
Width = 128,
Height = 72,
};
Button button = new Button
{
Content = "Press",
FontSize = 24,
};
button.Styles.Add(
new Style(x => x.OfType<Button>().Class(":pointerover"))
{
Setters =
{
new Setter(Button.BackgroundProperty, Brushes.Green), // This works.
new Setter(Button.ForegroundProperty, Brushes.Yellow),
}
});
button.Styles.Add(
new Style(x => x.OfType<Button>().Class(":pressed"))
{
Setters =
{
new Setter(Button.BackgroundProperty, Brushes.Blue), // This has no effect.
new Setter(Button.ForegroundProperty, Brushes.Red),
}
});
win.Content = button;
win.Show();
app.Run(win);
}
}
And here’s the button in a small window, first with the pointer outside the window, then inside, then inside and pressed:
Any idea how I can get the background to change when pressed?