我试图在ControlTemplate中的Storyboard中使用DynamicResource。但是,当我尝试这样做时,我会收到“无法冻结此故事板时间轴树以跨线程使用”的错误。
这里发生了什么?
很抱歉,您不能在样式(Style)或控件模板(ControlTemplate)中使用 DynamicResource。实际上,您也不能使用数据绑定表达式。
这里的情况是,必须确保样式和控件模板中的所有内容都可以跨线程安全使用,并且计时系统会尝试冻结样式和控件模板以使它们线程安全。但是,如果存在 DynamicResource 或数据绑定表达式,则无法将其冻结。
有关更多信息,请参见:MSDN 链接。请查看“在样式中进行动画”和“在控件模板中进行动画”部分(此文档页面相当长)。
对于解决方法(至少对于我的情况),请参见:WPF 论坛帖子。
希望这能帮助到某些人。我已经因此失去了足够多的头发。
Cory
在某些情况下,有一种解决方法:
简单的解决方案是在代码中使用sb
public static void ColorAnimation(FrameworkElement Obj, string From, string To, int Milliseconds)
{
Color from = ( Color )ColorConverter.ConvertFromString( From );
Color to = ( Color )ColorConverter.ConvertFromString( To );
{
ColorAnimation animation = new ColorAnimation();
animation.From = from;
animation.To = to;
animation.Duration = new Duration( TimeSpan.FromMilliseconds( Milliseconds ) );
Storyboard.SetTargetProperty( animation, new PropertyPath( "(Grid.Background).(SolidColorBrush.Color)", null ) );
Storyboard storyboard = new Storyboard();
storyboard.Children.Add( animation );
storyboard.Begin( Obj );
}
}
虽然您可以在ControlTemplate
中使用DynamicResource
,但是您不能在StoryBoard
中使用它。
我通过Opacity
(或Visibility
)hack来解决这个问题。
您可以向ControlTemplate
添加两个元素。每个元素都使用其中一个DynamicResources
,但只有一个元素可见。您可以通过Storyboard
设置每个元素的Visibility
或Opacity