我们可以转移所有画布的孩子吗?

时间:2014-04-13 20:19:04

标签: c# wpf canvas children

我正在做的是创建来自串行端口的数据的折线图。

我的代码部分是;

private void myTimer_Tick(object sender, EventArgs e)
    {

        if (X1 < Canvas.ActualWidth)
        {
            Line myLine = new Line();
            X1 = X1 + 1;
            X2 = X2 + 1;


            myLine.X1 = X1;
            myLine.Y1 = Y1;
            myLine.X2 = X2;
            myLine.Y2 = Y2; //Y2 comes from serial port
            myLine.Stroke = Brushes.Aqua;
            myLine.StrokeThickness = 2;
            Canvas.Children.Add(myLine);
            Y1 = Y2;




        }
        else
        {
            Canvas.Children.Clear();
            X1 = 0;
            X2 = 1;
        }
    }

从代码中可以看出,当行到达画布的末尾时,它会清除所有子项(行),并从画布的左侧开始重新开始(有点清爽)

现在我希望它开始将所有孩子(当用户看到线图时)向左移动。所以我们可以得到一个连续的动态情节。

有没有办法让所有画布的孩子都转移?

2 个答案:

答案 0 :(得分:0)

以此示例为例,将其应用到您的解决方案中。

请记住在减去左坐标之前检查左坐标是否大于零....

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Canvas x:Name="Canvas1" Background="BlueViolet" Margin="58,69,0,0">
            <Button Canvas.Top="20" Canvas.Left="100" Width="40" Height="30">Test 1</Button>
            <Button Canvas.Top="120" Canvas.Left="80" Width="40" Height="30">Test 2</Button>
        </Canvas>
        <Button Content="Button" HorizontalAlignment="Left" Margin="31,28,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
</Window>

MainWindow.xaml.Cs

private void Button_Click(object sender, RoutedEventArgs e)
{

        ShiftCanvasChildrenLeft(Canvas1, 10);
            //add new lines code here...
}

private void ShiftCanvasChildrenLeft(Canvas currentCanvas,Double shiftLeftBy )
{
        foreach (UIElement child in currentCanvas.Children)
        {
                //get the current left location
                Double currentLeftLocation = Canvas.GetLeft(child);
                //subtract 10 from the current location
                Double newLeftLocation = currentLeftLocation - shiftLeftBy;
                //move the child left
                Canvas.SetLeft(child, newLeftLocation);
        }

}

答案 1 :(得分:0)

您只需更改现有行的X1X2值:

foreach (var line in currentCanvas.Children.OfType<Line>())
{
    line.X1 -= 10;
    line.X2 -= 10;
}