InvalidOperationException for ColorAnimation for WPF Grid.Background inside ControlTemplate
我正在自定义股票WPF GroupBox控件。 当鼠标指针进入控制区域时,我需要为其背景实现彩色动画-例如,将背景颜色缓慢更改为预定义的颜色(将其设置为粉红色)。 我为此创建了一个自定义控件模板,其基本部分如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <ControlTemplate TargetType="{x:Type GroupBox}"> <Grid Name="MainGrid" SnapsToDevicePixels="true"> <!-- Control layout stuff with ContentPresenter --> </Grid> <ControlTemplate.Triggers> <EventTrigger RoutedEvent="MouseEnter"> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetName="MainGrid" Storyboard.TargetProperty="Background.(SolidColorBrush.Color)" To="Pink" Duration="0:0:1" /> </Storyboard> </BeginStoryboard> </EventTrigger> </ControlTemplate.Triggers> </ControlTemplate> |
但是,我无法使此动画生效。 我总是遇到一个未处理的类型异常:
'System.InvalidOperationException' occurred in
PresentationFramework.dll with additional information like this:
'Background' property does not point to a DependencyObject in path
'Background.(0)'
我用谷歌搜索了这个问题。 看来,我需要对TargetProperty使用正确的语法进行动画处理。 但是,我尝试了很多类似以下的变体,但在我的情况下它们都不起作用:
-
Background.Color -
(Panel.Background).Color -
(Panel.Background).(SolidColorBrush.Color) -
(Grid.Background).(SolidColorBrush.Color)
我搜索的方向不正确吗?
您的
例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <GroupBox> <GroupBox.Style> <Style TargetType="GroupBox"> <Style.Setters> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupBox}"> <Grid Name="MainGrid" SnapsToDevicePixels="true"> <Grid.Style> <Style TargetType="Grid"> <Setter Property="Background" Value="Blue"></Setter> </Style> </Grid.Style> <ContentPresenter/> </Grid> <ControlTemplate.Triggers> <EventTrigger RoutedEvent="MouseEnter"> <BeginStoryboard> <Storyboard> <ColorAnimation Storyboard.TargetName="MainGrid" Storyboard.TargetProperty="Background.Color" To="Pink" Duration="0:0:1" /> </Storyboard> </BeginStoryboard> </EventTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style.Setters> </Style> </GroupBox.Style> <Button Content="test" Width="200" Height="50"></Button> </GroupBox> |
完成此操作后,您可以轻松使用