Search code examples
c#avaloniauiavalonia

How to change a slider thumb in Avalonia Simple theme from C#?


I would like to change the style of my Avalonia Simple theme slider thumb. If I use the Fluent theme, and add a Style, I can make it wider. Here's how it looks in Fluent theme before adding the style:

enter image description here

Here's how it looks in Fluent theme after adding the style:

enter image description here

Here's the C# code to make it look like the second picture above:

using Avalonia;
using Avalonia.Controls;
using Avalonia.Styling;
using Avalonia.Controls.Primitives;

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.Fluent.FluentTheme());
        
        var win = new Window { Width = 500, Height = 50, };
        var slider = new Slider { Width = 480, };
        
        slider.Styles.Add(
            new Style(x => x.OfType<Slider>().Descendant().OfType<Thumb>())
            {
                Setters = { new Setter(Thumb.MinWidthProperty, 50.0), }
            });

        win.Content = slider;
        win.Show();
        app.Run(win);
    }
}

But, if I change this line:

app.Styles.Add(new Avalonia.Themes.Fluent.FluentTheme());

to this line:

app.Styles.Add(new Avalonia.Themes.Simple.SimpleTheme());

which switches from Fluent theme to Simple theme, the slider looks like this:

enter image description here

The style that makes the thumb wider in Fluent theme has no effect on the thumb in Simple theme.

How can I make the thumb wider from C# when I am using Simple theme?


Solution

  • This is due to the way the Fluent and Simple themes are implemented. You can see the Simple theme has a control template for the thumb that is using a Ellipse with a fixed size Width and Height. There are two ways you can work around this

    1. Drill down into the template itself and change the Ellipse.
    2. Create your own control template and replace the existing one.

    The second one is closest to what you already have. Instead of changing Thumb.MinWidthProperty, change the Thumb.Template property and set it to a new ControlTemplate of your own design.