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
.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With