Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force WPF scrollbar to only land on integer values

If I have a WPF scroll bar with both Change properties defined, why is it still possible to have a real value like 123.456 that is not a multiple of my steps?

<ScrollBar Minimum="-5000" Maximum="5000" SmallChange="1" LargeChange="25"></ScrollBar>

Is there a way to force a scroll bar to only set values of integers, multiples of the step, or both?

Most of the existing documentation on this issue seems directed towards WPF Sliders (which can use IsSnapToTickEnabled) or ScrollViewers (content controls using IScrollInfo), neither of which have equivalent solutions in ScrollBar.

like image 721
Scorpion Avatar asked Oct 19 '25 03:10

Scorpion


1 Answers

I believe you should be able to control the granularity of the stepping through a behavior. The endpoints (min and max) are the trickiest, but I'll stub out the rough idea here:

Attached Behavior:

public class StepScrollBehavior : Behavior<ScrollBar>
{
    protected override void OnAttached()
    {
        AssociatedObject.ValueChanged += AssociatedObject_ValueChanged;
        base.OnAttached();
    }

    protected override void OnDetaching()
    {
        AssociatedObject.ValueChanged -= AssociatedObject_ValueChanged;
        base.OnDetaching();
    }
    private void AssociatedObject_ValueChanged(object sender, 
            System.Windows.RoutedPropertyChangedEventArgs<double> e)
    {
        var scrollBar = (ScrollBar)sender;
        var newvalue = Math.Round(e.NewValue, 0);
        if (newvalue > scrollBar.Maximum)
            newvalue = scrollBar.Maximum;
        // feel free to add code to test against the min, too.
        scrollBar.Value = newvalue;
    }
}

Usage:

    <ScrollBar Minimum="-5000" Maximum="5000">
        <i:Interaction.Behaviors>
            <local:StepScrollBehavior/>
        </i:Interaction.Behaviors>
    </ScrollBar>
like image 104
Lynn Crumbling Avatar answered Oct 20 '25 23:10

Lynn Crumbling