'Can You Use A DynamicResource in a Storyboard Contained Within Style Or ControlTemplate

I am trying to use a DynamicResource in Storyboard contained within a ControlTemplate.

But, when I try to do this, I get a 'Cannot freeze this Storyboard timeline tree for use across threads' error.

What is going on here?



Solution 1:[1]

No, you can't use a DynamicResource in a Storyboard that is contained within a Style or ControlTemplate. In fact, you can't use a data binding expression either.

The story here is that everything within a Style or ControlTemplate must be safe for use across threads and the timing system actually tries to freeze the Style or ControlTemplate to make them thread-safe. However, if a DynamicResource or data binding expression is present, it is unable to freeze them.

For more info see: MSDN Link. Check out the 'Animate in a Style' and the 'Animate in a ControlTemplate' sections (this documentation page is rather long).

And for a workaround (at least for my scenario) see: WPF Forum Post.

Hope this helps someone. I've lost more than enough hair on it.

Cory

Solution 2:[2]

In some scenarios, there is a workaround:

  • introduce an attached property,
  • specify a style trigger for that introduced property with desired setter(s)

Solution 3:[3]

While you can have DynamicResource in a ControlTemplate, you just can't have one in a StoryBoard.

I worked around this with a Opacity (or Visibility) hack. You can add two elements to your ControlTemplate. Each of them uses one of the DynamicResources but only one of them is visible. You can set the Visibility or Opacity of each element via the Storyboard

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cplotts
Solution 2 Yury Schkatula
Solution 3 SWSBB