【发布时间】:2014-01-30 08:05:04
【问题描述】:
我在 Windows Phone 7.1 中使用 Canvases 和 ScrollViewer 构建视图:
<Grid x:Name="LayoutRoot">
<ScrollViewer x:Name="SV" Margin="0,8,0,-8" ManipulationCompleted="ScheduleBackground_ManipulationCompleted" Hold="SV_Hold">
<Canvas x:Name="ScheduleView" Grid.Row="1" Margin="0,0" Height="1560" Loaded="ScheduleView_Loaded" >
<Canvas x:Name="ScheduleBackground" >
<Grid x:Name="HoursLegend" />
</Canvas>
</Canvas>
</ScrollViewer>
</Grid>
它工作得很好。我可以看到我的整个画布。 现在我想添加一些交互,比如说当用户将手指放在画布的某个位置时绘制红色矩形。
// in page behind
private TaskCreator taskCreator;
private void SV_Hold(object sender, GestureEventArgs e)
{
taskCreator = new TaskCreator(ScheduleView, e);
}
private void ScheduleBackground_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
if (taskCreator != null)
{
taskCreator.Clear();
taskCreator = null;
}
}
我的类存储矩形:
class TaskCreator
{
private System.Windows.Controls.Canvas ScheduleView;
private System.Windows.Input.GestureEventArgs e;
private Rectangle rec;
public TaskCreator(System.Windows.Controls.Canvas ScheduleView, System.Windows.Input.GestureEventArgs e)
{
this.ScheduleView = ScheduleView;
this.e = e;
CreateTask();
}
private void CreateTask()
{
if (rec != null) throw new InvalidOperationException("Cannot create task without clear the previous rectangle");
rec = new Rectangle();
SolidColorBrush brush = new SolidColorBrush(Colors.Red);
rec.Stroke = brush;
rec.Fill = brush;
rec.Width = this.ScheduleView.ActualWidth;
rec.Height = 45;
Point pos = e.GetPosition(this.ScheduleView);
rec.Margin = new Thickness(0, pos.Y, 0, 0);
this.ScheduleView.Children.Add(rec);
}
public void Clear()
{
if (rec != null && ScheduleView != null)
{
this.ScheduleView.Children.Remove(rec);
rec = null;
}
}
}
而且它也有效。当用户在画布矩形上按住手指时,在他拿开手指后矩形消失。
现在我想在用户移动他的手指时移动这个矩形(但仍然握住它)。 我怎样才能做到这一点?我应该使用什么事件? 从我的角度来看,这里最大的问题是 ScrollViewer。绘制矩形后 SV 仍在工作(很好),但是当我滑行时,SV 正在移动并且我的矩形始终处于同一位置(相对于画布)。
我已经尝试过的:
我已将 ManipulationDelta="SV_ManipulationDelta" 添加到 SV:
private void SV_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
if (taskCreator != null)
taskCreator.Move(e);
}
在课堂上:
private TranslateTransform dragTranslation = new TranslateTransform();
internal void Move(System.Windows.Input.ManipulationDeltaEventArgs e)
{
dragTranslation.Y += e.DeltaManipulation.Translation.Y;
rec.RenderTransform = dragTranslation;
}
但它不起作用。
【问题讨论】:
标签: c# silverlight canvas windows-phone-7.1 scrollviewer