触控滚动条

WPF自带的ScrollViewer不支持在触控设备上进行下滑(上滑)滚动,所以得添加自定义控件
搭配滚动条样式使用更佳

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class TouchableScrollViewer : ScrollViewer
{
//触摸点的坐标
Point _startPosition;
//滚动条当前位置
double _startVerticalOffset;
double _startHorizontalOffset;
#region 依赖属性


public bool IsNoTouch
{
get { return (bool)GetValue(IsNoTouchProperty); }
set { SetValue(IsNoTouchProperty, value); }
}

/// <summary>
/// 禁止触摸
/// </summary>
public static readonly DependencyProperty IsNoTouchProperty =
DependencyProperty.Register("IsNoTouch", typeof(bool), typeof(TouchableScrollViewer), new PropertyMetadata(false));


#endregion
public TouchableScrollViewer()
{
TouchDown += TouchableScrollViewer_TouchDown;

TouchUp += TouchableScrollViewer_TouchUp;
}
private void TouchableScrollViewer_TouchDown(object sender, TouchEventArgs e)
{
if (IsNoTouch)
{
return;
}
//添加触摸移动监听
TouchMove -= TouchableScrollViewer_TouchMove;
TouchMove += TouchableScrollViewer_TouchMove;

//获取ScrollViewer滚动条当前位置
_startVerticalOffset = VerticalOffset;
_startHorizontalOffset = HorizontalOffset;

//获取相对于ScrollViewer的触摸点位置
TouchPoint point = e.GetTouchPoint(this);
_startPosition = point.Position;
}

private void TouchableScrollViewer_TouchUp(object sender, TouchEventArgs e)
{
//注销触摸移动监听
TouchMove -= TouchableScrollViewer_TouchMove;
}

private void TouchableScrollViewer_TouchMove(object sender, TouchEventArgs e)
{
if (IsNoTouch)
{
return;
}
//获取相对于ScrollViewer的触摸点位置
TouchPoint endPoint = e.GetTouchPoint(this);
//计算相对位置
double diffOffsetY = endPoint.Position.Y - _startPosition.Y;
double diffOffsetX = endPoint.Position.X - _startPosition.X;

//ScrollViewer滚动到指定位置(指定位置=起始位置-移动的偏移量,滚动方向和手势方向相反)
ScrollToVerticalOffset(_startVerticalOffset - diffOffsetY);
ScrollToHorizontalOffset(_startHorizontalOffset - diffOffsetX);
}
}