Search code examples
wpfdata-bindinganimationscaletransformlayouttransform

LayoutTransform animation on ScaleX and ScaleY is breaking binding with them


I have a custom class say 'MyCanvas' derived from wpf Canvas class. MyCanvas has a Dependency Property 'Scale' which specify the scale transform for the canvas. Now when the value of Scale changes I want to animate the transform from old value to new value. for that I am using LayoutTransform.BeginAnimation(...) method.

Code:

//This represents the time it will take to zoom
Duration zoomDuration = new Duration(TimeSpan.Parse("0:0:0.3"));

//Set up animation for zooming
DoubleAnimationUsingKeyFrames scaleAnimation = new DoubleAnimationUsingKeyFrames();
scaleAnimation.Duration = zoomDuration;
scaleAnimation.KeyFrames = GetAnimationSplines(newScale);
scaleAnimation.Completed += new EventHandler(
    (sender, e) => Scale = newScale);

// Start the scale (zoom) animations
LayoutTransform.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
LayoutTransform.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);

XMAL:

<Grid>
    <ItemsControl x:Name="Items">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <local:MyCanvas Scale="{Binding Scale, Mode=TwoWay}">
                    <local:MyCanvas.LayoutTransform UseLayoutRounding="True">
                        <ScaleTransform ScaleX="{Binding Scale, Mode=TwoWay}" 
                                        ScaleY="{Binding Scale, Mode=TwoWay}"/>
                    </local:MyCanvas.LayoutTransform>
                 </local:MyCanvas>
             </ItemsPanelTemplate>
         </ItemsControl.ItemsPanel>
    </ItemsControl>
</Grid>

But after executing this code, the binding of ScaleX and ScaleY with Scale ( a property in viewmodel) is breaking i.e. changing value of Scale does not change scale on canvas.

Error Message (using Snoop):

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Scale; DataItem=null; target element is 'ScaleTransform' (HashCode=796423); target property is 'ScaleX' (type 'Double')

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Scale; DataItem=null; target element is 'ScaleTransform' (HashCode=796423); target property is 'ScaleY' (type 'Double')

Please let me know if any one has solution for this. Thanks


Solution

  • Well, Today I was trying some thing and suddenly the issue got resolved. I did not understand how it start working. I made following changes to the code, which I tried earlier too.

    scaleAnimation.FillBehavior = FillBehavior.Stop;
    

    Can anyone explain this to me. Thanks.