C# Canvas.Children的迭代问题

C# Canvas.Children的迭代问题,c#,wpf,.net-4.0,C#,Wpf,.net 4.0,我正在迭代给定画布对象的所有子对象。问题是,这只影响到两个孩子中的一个。我在另一个类似事件中的另一个迭代工作得很好。我有这个,这样你可以拖动元素: private Point lastmousepoint; private void Window_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == System.Windows.Input.MouseButtonState.

我正在迭代给定画布对象的所有子对象。问题是,这只影响到两个孩子中的一个。我在另一个类似事件中的另一个迭代工作得很好。我有这个,这样你可以拖动元素:

    private Point lastmousepoint;   
    private void Window_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
        {                
            Point mousepos = e.GetPosition(this);
            foreach (UIElement element in canvas1.Children)
            {
                Canvas.SetLeft(element, Canvas.GetLeft(element) + (mousepos.X - lastmousepoint.X));
                Canvas.SetTop(element, Canvas.GetTop(element) + (mousepos.Y - lastmousepoint.Y));
                lastmousepoint = mousepos;
            }
        }
        e.Handled = true;
    }
    private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        lastmousepoint = e.GetPosition(this);
        e.Handled = true;
    }
    private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        e.Handled = true;
    } 
但这两个文本中只有一个在移动,而它们都应该移动。实际运动良好,工作正常

此代码

    private int CurrentScaleLevel = 0;
    private void Window_MouseWheel(object sender, MouseWheelEventArgs e)
    {
        foreach (UIElement element in canvas1.Children)
        {
            Point p = e.MouseDevice.GetPosition(element);
            Matrix m = element.RenderTransform.Value;
            if (e.Delta > 0)
            {
                CurrentScaleLevel++;
                m.ScaleAtPrepend(1.1, 1.1, p.X, p.Y);
            }
            else
            {
                CurrentScaleLevel--;
                m.ScaleAtPrepend(1 / 1.1, 1 / 1.1, p.X, p.Y);
            }
            Canvas.SetLeft(element, Canvas.GetLeft(element) + m.OffsetX);
            Canvas.SetTop(element, Canvas.GetTop(element) + m.OffsetY);
            m.Translate(-m.OffsetX, -m.OffsetY);
            element.RenderTransform = new MatrixTransform(m);
        }
        e.Handled = true;
    }

对这两个对象都有很好的影响,就像它应该的那样。

您可能不希望这样

lastmousepoint = mousepos;

foreach
循环中,因为在后续迭代中
(mousepos.X-lastmousepoint.X)
将始终为零,正如
(mousepos.Y-lastmousepoint.Y)
一样。添加0当然意味着没有移动。

您可能不想要

lastmousepoint = mousepos;

foreach
循环中,因为在后续迭代中
(mousepos.X-lastmousepoint.X)
将始终为零,正如
(mousepos.Y-lastmousepoint.Y)
一样。添加0当然意味着没有移动。

Genius。有时候,你所需要的只是第二双眼睛。天才。有时候,你所需要的只是第二双眼睛。