你能在样式或控件模板中使用DynamicResource来制作一个动画吗?

13

我试图在ControlTemplate中的Storyboard中使用DynamicResource。但是,当我尝试这样做时,我会收到“无法冻结此故事板时间轴树以跨线程使用”的错误。

这里发生了什么?

4个回答

31

很抱歉,您不能在样式(Style)或控件模板(ControlTemplate)中使用 DynamicResource。实际上,您也不能使用数据绑定表达式。

这里的情况是,必须确保样式和控件模板中的所有内容都可以跨线程安全使用,并且计时系统会尝试冻结样式和控件模板以使它们线程安全。但是,如果存在 DynamicResource 或数据绑定表达式,则无法将其冻结。

有关更多信息,请参见:MSDN 链接。请查看“在样式中进行动画”和“在控件模板中进行动画”部分(此文档页面相当长)。

对于解决方法(至少对于我的情况),请参见:WPF 论坛帖子

希望这能帮助到某些人。我已经因此失去了足够多的头发。

Cory


3
哇,这真的很糟糕,但至少谢谢你解释原因。 - Tomáš Kafka

1

在某些情况下,有一种解决方法:

  • 引入一个附加属性
  • 为该引入的属性指定一个样式触发器,并设置所需的setter

0

简单的解决方案是在代码中使用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 );
        }
    }

在 mouse_leave 事件中使用:(或也可在 mouse_enter 中)
如果(你的主题决定因素 1)ColorAnimation(MinimizeButton,“#FF333333”,“#00202020”,150); 如果(你的主题决定因素 2)ColorAnimation(MinimizeButton,“#FF32506E”,“#0032506E”,200);
等等...

0

虽然您可以在ControlTemplate中使用DynamicResource,但是您不能在StoryBoard中使用它。

我通过Opacity(或Visibility)hack来解决这个问题。 您可以向ControlTemplate添加两个元素。每个元素都使用其中一个DynamicResources,但只有一个元素可见。您可以通过Storyboard设置每个元素的VisibilityOpacity


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接