Search code examples
c#.netmaui

Is there a way to set an "Interval" or "Tick" on a Slider in .NET MAUI


Im trying to create a Slider that snaps only on whole numbers (0 - 100). I dont see any Property like "Interval" or "Tick" am i blind?


Solution

  • You can achieve this in a Slider .NET MAUI control by handling the data in the code behind it.

    The first thing you need to add is a Slider object with the ValueChanged event handler.

    To do so with XAML:

    <Slider
        Minimum="0"
        Maximum="100"
        ValueChanged="Slider_ValueChanged" />
    

    To do the same with C#:

    Slider slider = new()
        {
            Maximum = 100, // It is important to set the maximum value first.
            Minimum = 0
        };
    

    Now, you need the method that will run when the ValueChanged event is fired. This is where our logic will happen.

    // The value we want the slider to increment each time it updates
    readonly double sliderIncrement = 5;
    
    // The value for the slider we will be using.
    double sliderCorrectValue;
    
    // The actual method. If the Slider object was instantiated in C#, read below.
    private void Slider_ValueChanged(object sender, ValueChangedEventArgs e)
    {
        // Recognize the sender as a Slider object.
        Slider slider = (Slider)sender;
    
        // Get the slider value relative to the minimum,
        // needed to calculate valid values with increment.
        double relativeValue = slider.Value - slider.Minimum;
    
        // Check if the value is valid, based on our increment.
        if(relativeValue % sliderIncrement == 0)
        {
            // Value is valid
            sliderCorrectValue = slider.Value;
    
            // Update label text (optional)
            valueDisplayer.Text = sliderCorrectValue.ToString();
        }
    }
    

    This essentially creates a sliderCorrectValue double that stores our Slider's value if it is valid. Note that you need to use the sliderCorrectValue as your result value since the built-in Value Property of the Slider can still be an unwanted value.

    If you created the Slider in C#, use this to handle the ValueChanged event.

    slider.ValueChanged += (sender, e) =>
        {
            // The same code as above
        };
    

    However, I personally recommend always using XAML instead of C# when building the user interface for .NET MAUI apps.