TranslateTransform on a WPF Slidercontrol
I am trying to make it so that when the user holds down the left mouse button the slider control appears where the mouse is positioned and the user can move the slider control left/right. Once the left mouse button is removed it will pass the value into a method. I am completely stuck on this. I have the s开发者_如何学Golider control built, with a default position (the position can vary).
I have tried the following code to get the slider control to move to the mouses position but it does not do anything:
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;
}
Thanks in advance!
First you should capture mouse
then you should calculate mouse move distance
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;
}
}
I was able to do this fairly easily. I modified the slider code to include a name for the 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>
Then I hooked a click event to a button and used the following code:
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;
}
精彩评论