WPF如何在按下Shift键时更慢地滑动滑块

时间:2019-02-27 17:01:41

标签: c# wpf xaml

我有一个滑块,当单击滑块轨道上的任意位置时,我希望拇指移动到正确的位置,而当我按Shift键并拖动拇指时,希望移动得更慢。我知道如何检测按下Shift键的时间,但是我不知道如何放慢拇指的速度。任何帮助将不胜感激!

这是xaml代码:

<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>

和下面的代码:

void Slider_ShiftDrag(object sender, DragStartedEventArgs e)
{
    if (e != null && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
    {
        //What should I do here?
    }
}

1 个答案:

答案 0 :(得分:0)

The Preview

我写了一个假的滑块来实现您的目标。我不使用原生Thumb,因为原生Rectangle会捕获鼠标并始终跟随鼠标。因此,我写了Thumb而不是<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> 来进行拖动。

这是XAML:

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;
}

这是背后的代码:

{{1}}