我有一個包含Canvas的ScrollViewer。這個帆布上有一些可移動的UIElements。這是我的XAML代碼:Scrollable Canvas with ScrollViewer裏面的可移動物品
<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中?
問題是當ScrollViewer被禁用時,它內部的所有元素也被禁用。所以我不能移動它們:( –
我意識到這可能不是正確的路徑,但是如果擴展'Canvas'控件,則可以添加一個回調處理程序,以便在IsEnabledProperty被更改時被調用。然後在這個處理程序中,當Canvas被禁用時,可以將所有子項的'IsEnabled'屬性設置爲'true'。看看[這篇文章](http://social.msdn.microsoft.com/)。 com/Forums/vstudio/en-US/b965297b-abca-4c8f-a074-a6b46b7abdec/tabitem-isenabled-false-will-not-disable-all-child-controls)有一個類似的例子,但是對於一個TabItem控件代替。 – Sheridan