Search code examples
c#storyboarduwpuwp-xamlblend-2015

Get the position of an object moving using storyboard Universal Windows App


I have two Circle objects both drawn over a canvas. I'm moving one with a storyboard created in Blend for visual 2015 now i want to track the moving circle1's position to see when it reaches circle2 tried this:

  double x =  Canvas.GetLeft(circle1);

but this gets the value before the circle was moved and doesn't track its movement.

Anyone have any idea how to pull this off? thanks


Solution

  • When I use Blend for Visual Studio 2015, it generates some code like following:

    <Page ...>
        <Page.Resources>
            <Storyboard x:Name="Storyboard1" >
                <DoubleAnimation Duration="0:0:1" To="210" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="ellipse" d:IsOptimized="True"/>
                <DoubleAnimation Duration="0:0:1" To="114" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" Storyboard.TargetName="ellipse" d:IsOptimized="True"/>
            </Storyboard>
        </Page.Resources>
    
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <Canvas Width="600" Height="600">
                <Ellipse x:Name="ellipse" Fill="#FFF4F4F5" Height="100" Stroke="Black" Width="100" RenderTransformOrigin="0.5,0.5">
                    <Ellipse.RenderTransform>
                        <CompositeTransform/>
                    </Ellipse.RenderTransform>
                </Ellipse>
            </Canvas>
        </Grid>
    </Page>
    

    In this code, we can find that this movement is achieved by changing RenderTransform, especially TranslateX and TranslateY in storyboard. So the position of the circle is not changed. And while using Canvas.GetLeft method, it always returns the value that the circle is set.

    To get the "position", we can calculate with the TranslateX and TranslateY like:

    var transform = (circle1.RenderTransform as CompositeTransform);
    var x = Canvas.GetLeft(circle1) + transform.TranslateX;
    var y = Canvas.GetTop(circle1) + transform.TranslateY;