0
votes

I have a slider which I want the thumb moves to exact position when click on anywhere on the slider track and moves slower when I press Shift key and drag the thumb. I know how to detect when the shift key is pressed but I don't know how to slow down the thumb. Any help would be appreciated!

Here is the xaml code:

<Grid>
    <Slider x:Name="m_Slider" IsMoveToPointEnabled="True" Orientation="Vertical" 
            Height="200" Width="30" Minimum="0" Maximum="20" HorizontalAlignment="Center" 
            Thumb.DragStarted="Slider_ShiftDrag"/>
</Grid>

and here is the code-behind:

void Slider_ShiftDrag(object sender, DragStartedEventArgs e)
{
    if (e != null && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
    {
        //What should I do here?
    }
}
1
I'm pretty sure dragging just moves the thumb to where the cursor is. You'd have to slow the cursor movement or re-invent how sliders work.Andy
You'd better create a fake slider with an invisible thumb.walterlv

1 Answers

0
votes

The Preview

I've written a fake slider to achieve your goal. I don't use the native Thumb because the native one captures the mouse and always follow the mouse. So I write a Rectangle instead of Thumb to do the dragging.

This is the XAML:

<Grid Width="400" Height="32">
    <Rectangle x:Name="Tracker" Height="2" Fill="Gray" />
    <Rectangle x:Name="Thumb" Width="8" Height="32" Margin="-4 -16" Fill="DarkGray" HorizontalAlignment="Left" VerticalAlignment="Center"
               MouseDown="Thumb_MouseDown" MouseMove="Thumb_MouseMove" MouseUp="Thumb_MouseUp" LostMouseCapture="Thumb_LostMouseCapture">
        <UIElement.RenderTransform>
            <TranslateTransform x:Name="ThumbTranslation" />
        </UIElement.RenderTransform>
    </Rectangle>
</Grid>

And this is the code-behind:

private Point? _lastPoint;

private void Thumb_MouseDown(object sender, MouseButtonEventArgs e)
{
    _lastPoint = e.GetPosition(Tracker);
    Thumb.CaptureMouse();
}

private void Thumb_MouseMove(object sender, MouseEventArgs e)
{
    if (_lastPoint != null)
    {
        var currentPoint = e.GetPosition(Tracker);
        var offset = currentPoint - _lastPoint.Value;
        _lastPoint = currentPoint;
        if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
        {
            offset *= 0.2;
        }
        SetThumbTranslation(offset.X);
    }
}

private void Thumb_MouseUp(object sender, MouseButtonEventArgs e)
{
    _lastPoint = null;
    Thumb.ReleaseMouseCapture();
}

private void Thumb_LostMouseCapture(object sender, MouseEventArgs e)
{
    _lastPoint = null;
}

private void SetThumbTranslation(double offsetX)
{
    var x = ThumbTranslation.X + offsetX;
    x = Math.Max(x, 0);
    x = Math.Min(x, Tracker.ActualWidth);
    ThumbTranslation.X = x;
}