我在silverlight工作,我有一个MouseMove事件,它在画布上绘制一些东西(子窗口)
private void CanvasArt_MouseMove(object sender, MouseEventArgs e)
{
if (drawing)
{
Point current = e.GetPosition((UIElement)sender);
Line line = new Line() { X1 = start.X, Y1 = start.Y, X2 = current.X, Y2 = current.Y };
line.Stroke = new SolidColorBrush(Colors.Red);
line.StrokeThickness = 1;
CanvasArt.Children.Add(line);
start = current;
}
}
我在那个子窗口上有按钮
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
ExtendedImage MyCanvasImage = CanvasArt.ToImage();
CanvasArt.Children.Remove(line);// the 'line' is underlined in red marks and
//says 'line' doesnot exist in current context
}
如何解决这个问题?
答案 0 :(得分:2)
您可以清除Canvas的对象。
Canvas.Children.Clear()
这应该清除画布上的内容
答案 1 :(得分:1)
您需要能够识别Canvas
中的每个元素。如果只有少数几个,那么你可以在后面的代码中保存对它们的引用。但是,如果Canvas
中有许多元素,那么您可以使用Tag
属性来识别它们:
private void CanvasArt_MouseMove(object sender, MouseEventArgs e)
{
if (drawing)
{
Point current = e.GetPosition((UIElement)sender);
Line line = new Line() { X1 = start.X, Y1 = start.Y, X2 = current.X, Y2 = current.Y };
line.Tag = GetNextIdValue();
line.Stroke = new SolidColorBrush(Colors.Red);
line.StrokeThickness = 1;
CanvasArt.Children.Add(line);
start = current;
}
}
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
ExtendedImage MyCanvasImage = CanvasArt.ToImage();
// Retrieve line from CanvasArt.Children
Line line = (from c in CanvasArt.Children
where c.Tag.ToString() == "SomeValue"
select c).FirstOrDefault() as Line;
CanvasArt.Children.Remove(line);
}
您可以实现GetNextIdValue
方法以返回您想要的任何ID值。
答案 2 :(得分:1)
如果您只想删除该行,则可以将其引用存储为类中的私有字段。如果要删除所有元素,可以使用CanvasArt.Children.Clear()函数
答案 3 :(得分:0)
是的,line
是在CanvasArt_MouseMove
中声明的局部变量,您无法访问另一种方法的局部变量。
您有两个选择
CanvasArt.Children
集合