我有一个包含 Canvas 的 ScrollViewer。此画布上有一些可移动的 UIElement。这是我的 XAML 代码:
<ScrollViewer x:Name="Scroller" HorizontalScrollBarVisibility="Auto" Background="White">
<Canvas x:Name="MapCanvas" Width="4000" Height="4000">
<Button x:Name="TestBtn"
Content="My button"
Canvas.Left="250"
ManipulationStarted="MapItem_ManipulationStarted"
ManipulationDelta="MapItem_ManipulationDelta"
ManipulationCompleted="MapItem_ManipulationCompleted"
/>
</Canvas>
</ScrollViewer>
这是事件处理程序的代码:
private void MapItem_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
{
FrameworkElement btn = sender as FrameworkElement;
if (null == btn) return;
double left = Canvas.GetLeft(btn) + e.DeltaManipulation.Translation.X;
double top = Canvas.GetTop(btn) + e.DeltaManipulation.Translation.Y;
if (left < 0)
left = 0;
else if (left > MapCanvas.ActualWidth - btn.ActualWidth)
left = MapCanvas.ActualWidth - btn.ActualWidth;
if (top < 0)
top = 0;
else if(top > MapCanvas.ActualHeight - btn.ActualHeight)
top = MapCanvas.ActualHeight - btn.ActualHeight;
Canvas.SetLeft(btn, left);
Canvas.SetTop(btn, top);
e.Handled = true;
}
private void MapItem_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
{
Scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
Scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
e.Handled = true;
}
private void MapItem_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
{
Scroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
Scroller.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
e.Handled = true;
}
一切都很完美。但是,当 ScrollViewer 滚动到某个 HorizontalOffset 或 VerticalOffset 并且我单击或点击可见区域中的任何 UIElement 时,ScrollViewer 似乎会自动滚动到 HorisontalOffset == 0 和 VerticalOffset == 0。然后,在释放 UIElement 后,它会跳回来。我怎样才能避免这种行为并使 ScrollViewer 留在它的位置,而我将把 UIElement 拖到它里面的 Canvas 中?