我在Window.Resources中以“ MenuItem”样式创建了一些动画
<Style TargetType="MenuItem">
<Setter Property="Foreground" Value="White"/>
<Setter Property="FontSize" Value="10"/>
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="#2e3137"/>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Border x:Name="Bd" Padding="17,0,17,0" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="#2e3137" SnapsToDevicePixels="True" Uid="Border_38">
<ContentPresenter x:Name="ContentPresenter" Content="{TemplateBinding Header}" Grid.Column="1" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Uid="ContentPresenter_33"/>
</Border>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="MenuItem.MouseEnter">
<BeginStoryboard>
<Storyboard>
<ColorAnimation To="Gray" Storyboard.TargetProperty="(MenuItem.Background).(SolidColorBrush.Color)" Duration="0:0:0.3"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MenuItem.MouseLeave">
<BeginStoryboard>
<Storyboard>
<ColorAnimation To="Transparent" Storyboard.TargetProperty="(MenuItem.Background).(SolidColorBrush.Color)" Duration="0:0:0.3"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" TargetName="Bd" Value="0.56"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这个很好用。但是后来我意识到我需要将样式移动到Application.Resources,因为我需要在不同的窗口中使用此样式,但是当我将其移动时,动画会停止工作并显示错误:“背景”属性未指向路径中的DependencyObject'( 0)。(1)'。那么,这些资源之间有什么区别以及如何解决我的问题?谢谢。
UPD :发现不是菜单项而是标签的问题,奇怪的是我只将此样式设置为标签
<Style TargetType="Label">
<Setter Property="Foreground" Value="White"/>
<Setter Property="FontSize" Value="14"/>
</Style>