在WPF Slidercontrol上进行TranslateTransform

时间:2011-06-11 03:55:56

标签: c# wpf slider

我试图这样做,以便当用户按住鼠标左键时,滑块控件出现在鼠标所在的位置,用户可以左/右移动滑块控件。删除鼠标左键后,它会将值传递给方法。我完全坚持这个。我建立了滑块控件,默认位置(位置可以变化)。

我尝试使用以下代码让滑块控件移动到鼠标位置,但它没有做任何事情:

        private void Button_Click(object sender, RoutedEventArgs e)
    {
          TranslateTransform currentTransform = new TranslateTransform();
          currentTransform = slider.RenderTransform as TranslateTransform;
            currentTransform.X = Mouse.GetPosition(Deck_Door).X;
            currentTransform.Y = Mouse.GetPosition(Deck_Door).Y;

        slider.Visibility = Visibility.Visible;

    }

提前致谢!

2 个答案:

答案 0 :(得分:0)

首先你应该抓住鼠标 那么你应该计算鼠标移动距离

protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
   this.CaptureMouse();

    //Show slider here
}

protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
{
   this.ReleaseMouseCapture();

    //Hide slider here and get it's value
}

Point previousMousePosition;

protected override void OnPreviewMouseMove(MouseEventArgs e)
{
    if (this.IsMouseCaptured)
    {
        Point point = e.GetPosition(this);

        double d = point.X - previousMousePosition.X;

        //you can use this value to change the slider's value

        this.previousMousePosition = point;
    }
}

答案 1 :(得分:0)

我能够相当容易地做到这一点。我修改了滑块代码以包含translateTransform的名称:

<Slider x:Name="slider" 
        TickFrequency="1"
        Value="1"
        IsSnapToTickEnabled="True"
    IsMoveToPointEnabled="True"
        Minimum="0"
        Maximum="10"
    ValueChanged="slider_ValueChanged"
        AutoToolTipPlacement="BottomRight"
        Grid.Column="0" VerticalAlignment="Top" Margin="0,-3,51.5,0"
        Thumb.DragCompleted="slider_DragCompleted" >
    <Slider.RenderTransform>
        <TranslateTransform x:Name="mySliderTransform" />
    </Slider.RenderTransform>
</Slider>

然后我将一个click事件挂钩到一个按钮并使用以下代码:

        private void Button_Click(object sender, RoutedEventArgs e)
    {
        slider.Visibility = Visibility.Visible;
        slider.Value = 1;

        // get the mouse positions
        string x = Mouse.GetPosition(this).X.ToString();
        string y = Mouse.GetPosition(this).Y.ToString();

        // convert the mouse position to a double
        var X = Convert.ToDouble(x);
        var Y = Convert.ToDouble(y);

        // reset the slider transform and apply the coordinates of the mouse position.
        mySliderTransform.X = 0;
        mySliderTransform.Y = 0;
        mySliderTransform.X = X - 20;
        mySliderTransform.Y = Y;
    }