Procedural animation problem with dynamically named elements RRS feed

  • Question

  • I have a situation where I am producing a large amount of visual elements on the fly that I want to be able to apply animations to.  Since we have to supply a particular animation a "TargetName" I assumed I could just name each of my visuals using their HashCode to make each name unique. Each of the visuals is actually a UserControl with which I've set up to have a RenderTransform (a TransformGroup composed of a TranslateTransform and a ScaleTransform, in that relative order). To trigger the animation I have the following code:


            void myVisual_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    MyVisual myVisual = sender as MyVisual;
    DoubleAnimation myAnimation = (DoubleAnimation)myVisual.GetValue(MyAnimationProperty);
                myVisual.Name = "visual" + myVisual.GetHashCode().ToString();
    myAnimation.SetValue(Storyboard.TargetNameProperty, myVisual.Name);
    myAnimation.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("(UIElement.RenderTransform).Children[1].ScaleX"));
                Storyboard story = new Storyboard();
    myVisual.Resources.Add("sb" + story.GetHashCode().ToString(), story);

    At the point where I enter this callback, 'myVisual' has already had it's RenderTransform set up appropriately (which doesn't seem to be the problem anyway). However, when I try to run the animation I get an exception complaining about the name of the visual:

    Cannot resolve TargetName visual22063888.

    Anyone have any clues as to why I'm getting this exception? Does it matter whose resources I add the Storyboard to? I've tried two scenarios. I first added each storyboard to the control who contains the visual hierarchy where all the dynamic visuals will live. When that didn't work (with the error mentioned above), I tried moving the storyboard to the resources of each unique 'MyVisual' element, but that produced the same results. Thanks for the help!


    Monday, October 13, 2008 4:18 PM


  •  Well, I figured out a solution. Instead of supplying a TargetName for each animation, if I instead use the static Storyboard method 'SetTarget' and just supply each 'myVisual' element as the target, everything works as expected. It still seems as if the code I posted above should work, but now it doesn't seem that important.

    Monday, October 13, 2008 4:49 PM