Using a Storyboard animation on a programmatically-added control Using a Storyboard animation on a programmatically-added control wpf wpf

Using a Storyboard animation on a programmatically-added control


I wouldn't hassle with the NameScopes etc. and would rather use Storyboard.SetTarget instead.

var b = new Button() { Content = "abcd" };stack.Children.Add(b);var fade = new DoubleAnimation(){    From = 0,    To = 1,    Duration = TimeSpan.FromSeconds(5),};Storyboard.SetTarget(fade, b);Storyboard.SetTargetProperty(fade, new PropertyPath(Button.OpacityProperty));var sb = new Storyboard();sb.Children.Add(fade);sb.Begin();


I solved the problem using this as parameter in the begin method, try:

sb.Begin(this);

Because the name is registered in the window.


I agree, the namescopes are probably the wrong thing to use for this scenario. Much simpler and easier to use SetTarget rather than SetTargetName.

In case it helps anyone else, here's what I used to highlight a particular cell in a table with a highlight that decays to nothing. It's a little like the StackOverflow highlight when you add a new answer.

    TableCell cell = table.RowGroups[0].Rows[row].Cells[col];    // The cell contains just one paragraph; it is the first block    Paragraph p = (Paragraph)cell.Blocks.FirstBlock;    // Animate the paragraph: fade the background from Yellow to White,    // once, through a span of 6 seconds.    SolidColorBrush brush = new SolidColorBrush(Colors.Yellow);    p.Background = brush;    ColorAnimation ca1 = new ColorAnimation()    {            From = Colors.Yellow,            To = Colors.White,            Duration = new Duration(TimeSpan.FromSeconds(6.0)),            RepeatBehavior = new RepeatBehavior(1),            AutoReverse = false,    };    brush.BeginAnimation(SolidColorBrush.ColorProperty, ca1);