views:

12

answers:

0

I'm just playing around with WPF at the moment and I don't entirely understand how it works, but this is baffling. I have a piece of code which creates a TextBlock with a RenderTransform and animates it scrolling across the screen. This is pretty much a procedural translation of something Josh Smith wrote to demonstrate how you might do a marquee tag.

This is the bit of code :

NameScope.SetNameScope(this, new NameScope());

var anim = new DoubleAnimation
           {
               From = 300,
               To = -100,
               By = -5,
               Duration = new Duration(TimeSpan.FromSeconds(10)),
               RepeatBehavior = RepeatBehavior.Forever
           };

var transform = new TranslateTransform();
this.RegisterName("translate", transform);

var text1 = new TextBlock {Text = "Hello", RenderTransform = transform};
Storyboard.SetTargetName(anim, "translate");
Storyboard.SetTargetProperty(anim, new PropertyPath(TranslateTransform.XProperty));

var myStoryBoard = new Storyboard();
myStoryBoard.Children.Add(anim);
this.Children.Add(text1);
myStoryBoard.Begin(this, true);

I thought it might be neat to have a class which derives from StackPanel implement this, so, because this lived in the OnInitialized method on the original window, I moved it to the same method in the new StackPanel derived class :

public class MyPanel : StackPanel
{
    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        //code went here...
    }
}

But if I do this, I get a "Stack empty. Error in markup file" XamlParseException thrown.

Oddly, if I move the entire function into the constructor of MyPanel, everything works fine.

Can anyone explain what I'm doing wrong?